Equals method

As you may know overriding the equals method could be very important when writing java classes, consider the following:

Always check the implemetation to be:

  • Reflexive: For any x != null x.equals(x) must be true.
  • Symetric: For any x,y != null : x.equals(y) must be equals to y.equals(x).
  • Transitive: For any x,y,z != null : if x.equals(y) is true and y.equals(z) is true, x.equals(z) must be true.
  • Consistent: For any x,y != null : x.equals(y) must returns the same result across invocations unless, the state of of x or y changes.
  • Implement hashcode: If you are overriding equals also override  hashCode()

Also would be good to check:

  • Override equals(Object obj): Using @Override
  • Use instanceof inside the equals method.

A tool that simplify this is:

References:

  • Bloch Joshua, 2008.  Item 8 “Obey the general contract when overriding equals”  Effective Java Second Edition,pp.33.

One thought on “Equals method

  1. Use the following when comparing nested objects:

    (member == cmpObj.member || (member !=null && member.equals(cmpObj.member)) )

Leave a comment