Witscale Test Center

14.6 Overriding the equals() and hashCode() methods > 14.6.3 Method contract for the equals() method


14.6.3 Method contract for the equals() method

The javadoc comments in the Object class clearly states how the equals() method should be implemented. These set of rules are defined using the mathematical terms for explaining equivalence relation.

The equals() method should be  reflexive.

It means that if you are comparing an object with itself using equals(), it should return true. For instance, for any reference ref, the call ref.equals(ref) should return true.

The equals() method should be  symmetric.

 When you are comparing two objects using equals(), if first object is found equal to second object, the second object must also be equal to first object. For instance, for any two references ref1 and ref2, if ref1.equals(ref2) returns true then  ref2.equals(ref1) should also return true.

The equals() method should be  transitive.

 To understand transitivity, assume that you have three references ref1, ref2, and ref3.  Now if ref1.equals(ref2) returns true and ref2.equals(ref3) returns true, then ref1.equals(ref3) must return true.

The equals() method should be  consistent.

 It means that if you invoke equals() multiple times and the objects on which it is invoked are not changed, then equals() should consistently return the same result. For instance if you have two references ref1 and ref2, multiple invocations of ref1.equals(ref2) consistently return the same result (EITHER true or false) assuming that no information used for comparisons in equals() is        modified.

The equals() method should return false while comparing any reference (which is not null) with a null reference. 

For instance, for any reference ref1, ref1.equals(null) should return false.

 

You cannot compare a null reference with any other reference using the equals() method. For instance, following  code will throw a NullPointerException at runtime.   


    Bird b = null;
  System.out.println(b.equals(anyBird));
// throws exception

 

Besides these rules, there is one crucial requirement for the equals() method. The equals() and hashCode() are bound together by a joint contract that specifies if two objects are considered equal using the equals() method, then they must have identical hashcode values. So to be truly safe, your rule of thumb should be if you override equals(), override hashCode()as well. So let’s switch over to hashCode() and see how that method ties in to equals().