Specification of the equals(Object) Method in Java
The specification of Java's standard libraries imposes
certain invariants that must be satisfied by any
equals(Object) method we define.
The
equalsmethod implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value
x,x.equals(x)should returntrue.- It is symmetric: for any non-null reference values
xandy,x.equals(y)should return true if and only ify.equals(x)returnstrue.- It is transitive: for any non-null reference values
x,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue.- It is consistent: for any non-null reference values
xandy, multiple invocations ofx.equals(y)consistently returntrueor consistently returnfalse, provided no information used inequalscomparisons on the objects is modified.- For any non-null reference value
x,x.equals(null)should returnfalse.
The "provided no information...is modified" qualification
on the next-to-last invariant helps to explain why we have
been using immutable data types so far in this course.
With mutable data types, everything becomes more complicated.
In particular, x.equals(y) may return true
for one call but return false a moment later,
after some concurrent thread has changed the state of
x or y.
When we define an equals method, we must also
define a hashCode method:
Note that it is generally necessary to override the
hashCodemethod whenever this method is overridden, so as to maintain the general contract for thehashCodemethod, which states that equal objects must have equal hash codes.