Pages

Monday, July 5, 2010

Overriding HashCode

Overriding the default implementations of the Java class equals method provides a higher degree of semantic comparability between object instances. Under the default implementation, two references are equal only if they refer to the exact same object.

Cases where hashCode must be overridden include the following:
  • if a class overrides the equals method it must override hashCode
  • when they are both overridden, equals and hashCode must use the same set of fields
  • if two objects are equal, then their hashCode values must be equal as well
If equals() and hashCode() are not overridden, no adverse effects would occur unless the objects are used in a HashMap or other hash-based collection. If such objects are used in hash-based collections, we would not be able to reliably retrieve objets unless we used exactly the same object instance in the get() call as was used in the put() call.

A simple way of overriding the equals and hashcode methods in Eclipse is to generate them using the menu/context menu Source -> Generate hashCode() and equals().

All hash-based collections assume that an object's hash value will not change whilst it is in use as a key in the collection. If assumption were violated unpredictable results would occur.

0 comments:

Post a Comment

 
Powered by Blogger