Saturday, 14 May 2011

Implementing equals

Object class have methods like equals() and hashcode(). These methods have their own contracts which have to be fulfilled to override them.
 
Default implementation of equals() in object class

The default implementation of equals() in Object class is based on the == operator: Two objects are equal if and only if they are the same object. Naturally, most classes should define their own alternative implementation of this important method.

 
 
Contract of equals method:

Implementing equals() correctly is not straightforward. The equals() method has a contract that says the equality relation must meet these demands:

  • It must be reflexive. For any reference x, x.equals(x) must return True.
  • It must be symmetric. For any two nonnull references x and y, x.equals(y) should return the exact same value as y.equals(x).
  • It must be transitive. For any three references x, y, and z, if x.equals(y) and y.equals(z) are True, then x.equals(z) must also return True.
  • It should be consistent. For any two references x and y, x.equals(y) should return the same value if called repeatedly (unless, of course, either x or y were changed between the repeated invocations of equals()).
  • For any nonnull reference x, x.equals(null) should return False.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Steps to be taken when implementing equals()

No comments:

Post a Comment