hashCode and equals method are frequently asked in Java interviews. In general, we do not override both methods but there are some scenarios/requirements when we have to override these two methods. One such scenario when we store user-defined objects in Collection classes that make use of hashing algorithm. i.e. HashTable, HashSet and HashMap.
Interview Question: Create a Map which contains address of each employee and uses employee object as a key. Store address of some employees in this map. Now create a method that accepts Map and Employee object as parameters and returns address of this employee.
Approach 1 (Without overriding hashCode and equals methods)
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)
304, Marol Mahrisi, Mumbai, 400069
We 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.
This article is contributed by Sajid Ali Khan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Why to Override equals(Object) and hashCode() method ?
- equals() and hashCode() methods in Java
- Method Class | hashCode() Method in Java
- JavaTuples hashcode() method
- Set hashCode() method in Java with Examples
- HashSet hashCode() method in Java with Example
- AbstractSequentialList hashCode() method in Java with Example
- IdentityHashMap hashCode() Method in Java
- BigInteger hashCode() Method in Java
- CopyOnWriteArrayList hashCode() method in Java
- DecimalFormat hashCode() method in Java
- BigDecimal hashCode() Method in Java
- YearMonth hashCode() method in Java
- Importance of Hashcode method in Java
- DecimalStyle hashCode() method in Java with Example