VOOZH about

URL: https://www.geeksforgeeks.org/dsa/interesting-interview-question-hashcode-equals-method/

⇱ Interesting interview question on hashCode and equals method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Interesting interview question on hashCode and equals method

Last Updated : 25 Sep, 2017
Prerequisite: Equal and Hashcode Methods in Java , Why to override equal and hashcode methods 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)

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, 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.
Comment
Article Tags:
Article Tags: