![]() |
VOOZH | about |
Approach 1 (Without overriding hashCode and equals methods)
Output:Exception in thread "main" java.lang.NullPointerException at Test.getAddress(Test.java:44) at Test.main(Test.java:59)We expected the output as address of employee, but we get NullPointerException and that is pretty straight forward. new Employee(110, "Sajid Ali Khan") in Map and new Employee(110, "Sajid Ali Khan") in argument are two different instances. Hence we get NullPointerException because when we do map.get(emp), it returns null.
Approach 2 (Overriding hashCode and equals method)
Output:304, Marol Mahrisi, Mumbai, 400069We get the expected output and that is because we have override hashCode and equals method properly in our code. When we do map.get(emp), it internally calls our overriding hashCode method which results in same hashcode as of employee object used as key in Map. Once right bucket is find, equals method will be called and matches all values of both Employee object. As a result, we get correct address of Employee object.