Overriding equals and hashCode methods in Java

The default implementation of equals() method is provided by Object compares memory location and only return true if the reference variable is pointing to same memory. When overriding equals method, here are the rules that the equals method must obey:
  1. Reflexive: Object must equal to itself.
  2. Symmetric: if a.equals(b) is true and then b.equals(a) must be true.
  3. Transitive: if a.equals(b) is true and then b.equals(c) is be true, then c.equals(a) must be true.
  4. Consistent: multiple invocations of a.equals(b) consistently return true or false, provided no information used in equals comparisons on the objects are modified.
  5. Null comparison: if a.equals(null) should return false.

Step to override equals method

  1. Return true if they are having same address
  2. Return false if the reference object is null
  3. Check subclass or same class by instanceof method
  4. Type cast the object
  5. Compare individual attributes and should avoid NullPointerException
Suppose you are creating a Money class with currency and amount. You could possibly decide that two Money objects must be referring to the same money if they have exactly the same currency and amount fields.

Notice also how verbose Java is, even in an operation as basic as comparing Money for equality. I preferably use the JDK7’s Objects and Guava’s Objects as below:
The new edition of the code will become easier.

Equals and hashCode contract in Java

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, HashTable, or WeakHashMap…, the hashCode() of key objects that you put into Collection never changes while the object is in the collection.
For equals and hashCode contract, there are two ideas:
  1. If two objects are equal by equals() then their hashCode must be same.
  2. If two objects are having the same hashCode then it does not mean that both objets are equal by equals() method. They might be un-equal also, so their hashCode might be the same or different.

No comments:

Post a Comment