Equivalence Relation of the equals() Method – Object Comparison


Equivalence Relation of the equals() Method

An implementation of the equals() method must satisfy the properties of an equivalence relation:

  • Reflexive: For any reference self, self.equals(self) is always true.
  • Symmetric: For any references x and y, if x.equals(y) is true, then y.equals(x) is true.
  • Transitive: For any references x, y, and z, if both x.equals(y) and y.equals(z) are true, then x.equals(z) is true.
  • Consistent: For any references x and y, multiple invocations of x.equals(y) will always return the same result, provided the objects referenced by these references have not been modified to affect the equals comparison.
  • null comparison: For any non-null reference obj, the call obj.equals(null) always returns false.

The general contract of the equals() method is defined between objects of arbitrary classes. Understanding its criteria is important for providing a proper implementation.

Reflexivity

This rule simply states that an object is equal to itself, regardless of how it is modified. It is easy to satisfy: The object passed as an argument and the current object are compared for object reference equality (==), the same as the default behavior of the Object.equals() method. If the references are aliases, the equals() implementation returns true.

if (this == argumentObj)
  return true;
// …

The reflexivity test can usually be an operand of the short-circuit conditional-OR operator (||) in a return statement, where if the reflexivity test is true, other criteria for equality comparison are not evaluated:

Click here to view code image

return (this == argumentObj)
    || (/* Other criteria for equality. */);

Symmetry

The expression x.equals(y) invokes the equals() method on the object referenced by the reference x, whereas the expression y.equals(x) invokes the equals() method on the object referenced by the reference y. If x.equals(y) is true, then y.equals(x) must be true.

If the equals() methods invoked are in different classes, the classes must bilaterally agree whether their objects are equal or not. In other words, symmetry can be violated if the equals() method of a class makes unilateral decisions about which classes it will interoperate with, while the other classes are not aware of this. Avoiding interoperability with other (non-related) classes when implementing the equals() method is strongly recommended.

Leave a Reply

Your email address will not be published. Required fields are marked *