Thursday, September 5, 2013

Why hashCode should also be overridden when equals is overridden?

Why hashCode should also be overridden when equals is overridden?

Because, they both serve the same purpose but in different contexts.
hashCode() method is used in hashtables to determine the equality of  keys. 


When an application is executed, the hashcode (an integer) returned for an object should be same till another execution of that application.
Coming to the important point which is the contract between hashCode and equals method,
  • if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and obj2.hashCode() must return same integer.

Override hashCode Method

To honor the above contract we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.

Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it. This is the lowest form of equality implementation and provides guaranteed results for hastables implementation. When we override equals() and change the meaning of equality for an object then the same should be reflected by overriding the hashCode method.


No comments:

Post a Comment