12/10/17

hashcode and equals override - interview questions



Tip: Analyse impact on put and get method

Case 1: -
hashcode override - No 
equals override - No

What Will Happen-
when you try to get object using new key —> Object class hashcode will work —> new key will have different hashcode —> you will not find the object in hashmap.
Object class hashcode implementation - converting the internal address of the object into an integer


Impact
the same key will not override 
you won’t find the object.

———————————
Case 2: -
hashcode override - Yes 
equals override - No

What Will Happen-
same keys will have the same hashcode —> collision will occur —> object class’s equals(default) will work -> Instead of override key, all objects will be there
(The default equals() method on java.lang.Object compares memory addresses -> so they all will be treated as diff object.)

Impact
same key -> same hashcode —> they will all go to the same bucket-> will have a collision but absence of equals it won’t find the object.


———————————
Case 3: -
hashcode override - No 
equals override - Yes

What Will Happen-
if two objects are equal, hashcode should also be equal. 
if hashcodes are equal then they should go to the same bucket
there will be a collision and it will need custom equals method to check. otherwise, object’s equal will be called and won’t work.

Impact
They will all go to different bucket -> key will also have diff hashcode -> you won’t find object


———————————
Case 4: -
hashcode override - Yes 
equals override - Yes

Impact

Everything works fine

Keywords:- java, equals, hashcode, java (programming language), tutorial, java hashcode, equals and hashcode, java equals and hashcode, hashmap, collection, equals and hashcode in java, equals and hashcode contract, hashset, java interview question, map, hashcode in java, programming, programming language (software genre), java programming tutorial, method, java programming, hashcode method in java, core java, java tutorial