Recently I read through this
Developer Works Document.
The document is all about defining hashCode() and equals() effectively and correctly, however I am not able to figure out why we need to override these two methods.
How can I take the decision to implement these methods efficiently?
Joshua Bloch says on Effective Java
Let’s try to understand it with an example of what would happen if we override
equals()without overridinghashCode()and attempt to use aMap.Say we have a class like this and that two objects of
MyClassare equal if theirimportantFieldis equal (withhashCode()andequals()generated by eclipse)Imagine you have this
Override only
equalsIf only
equalsis overriden, then when you callmyMap.put(first,someValue)first will hash to some bucket and when you callmyMap.put(second,someOtherValue)it will hash to some other bucket (as they have a differenthashCode). So, although they are equal, as they don’t hash to the same bucket, the map can’t realize it and both of them stay in the map.Although it is not necessary to override
equals()if we overridehashCode(), let’s see what would happen in this particular case where we know that two objects ofMyClassare equal if theirimportantFieldis equal but we do not overrideequals().Override only
hashCodeIf you only override
hashCodethen when you callmyMap.put(first,someValue)it takes first, calculates itshashCodeand stores it in a given bucket. Then when you callmyMap.put(second,someOtherValue)it should replace first with second as per the Map Documentation because they are equal (according to the business requirement).But the problem is that equals was not redefined, so when the map hashes
secondand iterates through the bucket looking if there is an objectksuch thatsecond.equals(k)is true it won’t find any assecond.equals(first)will befalse.Hope it was clear