Monday, 29 August 2011

Equals and hashcode method

are two of the most important non final methods in the Object class which if not coded properly can lead to problems when used in collection and are difficult to detect and debug. Hence it is important to understand the contract of the two methods to code for the same.
Equals method, defined in the object class checks if the references of the objects are the same, i.e they point to the same memory location. You can override this method to check if the two objects are meaningfully equivalent (though residing in different memory location). The following contract needs to be observed while coding the equals method

  • Reflexive - o1.equals(o1), an object should be equal to itself
  • Symmetric -  o1.equals(o2), if and only o2.equals(o1)
  • Transitive -  o1.equals(o2), and o2.equals(o3) implies o1.equals(o3)
  • Consistent - o1.equals(02), returns the same result as long as the objects are not modified.
  • Null Comparison - !o1.equals(null), which means any object is not equal to null, it should return false.
  • Equals and hashCode - If two objects are equal then their hashCode should be equal as well, however the reverse is not true. (It is mandatory to define hashCode if you define equals method)
HashCode method returns an integer and is supported for the benefit of hashing based collections like HashMap,Hashtable etc. The contract for this method are
  • Consistent - Whenever the method is invoked on the same object more than once during the lifetime of an application, it should always return the same result
  • If two objects are equals as per the equals method then calling the hashCode method in each of the two objects must consistently return the same integer result. If a field is not used in equals method it should not be used in hashCode method as well.
  • If two objects are unequal as per the equals methods then calling the hashCode method in each of the two objects can either return the same or different integer result.

No comments:

Post a Comment