Tuesday, June 16, 2009

Simply hashcode

In Java, here are the key things to remember about hashcode:
  • If you override equals method also override hashcode method. The default implementation of hashcode returns the 32-bit internal JVM address of the object. So if you do not override hashcode, the object cannot be used in data structures that use hashing mechanism. 
  • If two objects are equal, their hashcodes must be equal. However the reverse is not true i.e. if the hashcodes are equal, the objects may or may not be equal/same.
  • If hashcodes of 2 objects are NOT same, the two objects are NOT equal.
  • If both equals and hashcode are overridden, they must use the same set of fields. Equals may use more fields than hashcode uses but it must use all the fields that hashcode uses. The fields must be final i.e. immutable. If the fields are changeable, you may not get accurate results.
  • Hashcode DOES NOT provide a unique identifier for an object.
  • Hashcodes can be negative.

No comments:

Post a Comment