Sub topic 3
The equals contract
This chapter assumes you can write basic Java classes, know the difference between primitives and object references, and have overridden methods before. It covers the rules an equals method must follow, why each rule exists, and how real code breaks them. Writing a correct equals step by step comes in the next chapter.
Why equals has a contract
Object.equals is declared as public boolean equals(Object obj), and its default body is return this == obj;. Every class inherits identity comparison until it overrides the method.
When you override equals, you replace that definition with your own. The JDK does not enforce any rules on your version. The compiler accepts an equals that always returns true. Library code, however, assumes the rules in the Object.equals Javadoc hold. List.contains, List.remove, HashSet, HashMap, Collections.binarySearch helpers, and most test frameworks all depend on them. If your method breaks a rule, those classes do not throw an exception. They return wrong answers.
The five rules
The contract describes an equivalence relation on non-null references, plus two extra rules about stability and null.
| Rule | Statement | Typical way to break it |
|---|---|---|
| Reflexive | `x.equals(x)` is `true` | Comparing a field that is `NaN` with `==` |
| Symmetric | `x.equals(y)` if and only if `y.equals(x)` | Accepting a foreign type in one direction only |
| Transitive | If `x.equals(y)` and `y.equals(z)`, then `x.equals(z)` | Subclass that ignores its extra field against the superclass |
| Consistent | Repeated calls give the same answer while nothing compared has changed | Depending on a network lookup, the clock, or random values |
| Non-null | `x.equals(null)` is `false` | Dereferencing the argument before checking it |
"Consistent" has a precise scope. If the objects are mutable, the answer may change when their fields change. The rule forbids equals from changing its answer when nothing has changed.
Reflexivity
Reflexivity is the rule that is hardest to break by accident, and the one NaN breaks. If you compare double fields with ==, an object holding Double.NaN is not equal to itself, because Double.NaN == Double.NaN is false. Double.compare(a, b) == 0 treats NaN as equal to itself, so use it. The "Floating-point, array, and nullable fields" chapter covers this in detail.
A fast path such as if (this == o) return true; guarantees reflexivity regardless of field contents. It also saves work in the common case where an object is compared with itself.
Symmetry
Symmetry fails when your class tries to be equal to a class you do not control. The classic case is a case-insensitive string wrapper that also accepts plain String values:
public class SymmetryDemo {
static final class CiString {
private final String s;
CiString(String s) {
this.s = s;
}
@Override
public boolean equals(Object o) {
if (o instanceof CiString) {
return s.equalsIgnoreCase(((CiString) o).s);
}
if (o instanceof String) { // tries to interoperate with String
return s.equalsIgnoreCase((String) o);
}
return false;
}
@Override
public int hashCode() {
return s.toLowerCase().hashCode();
}
}
public static void main(String[] args) {
CiString cis = new CiString("Java");
String plain = "java";
System.out.println(cis.equals(plain)); // true
System.out.println(plain.equals(cis)); // false
}
}String.equals returns false for anything that is not a String, and you cannot change that. The two directions disagree, so the result depends on which side the caller happens to write first. A List<String> that is searched with a CiString may find it, while cis searching the list may not.
The fix is to have CiString.equals accept only CiString instances. A class cannot be equal to a type whose equals method it does not control.
Transitivity
Transitivity usually fails in class hierarchies. Suppose a subclass adds a field and tries to restore symmetry by ignoring that field when it compares against a plain superclass instance:
public class TransitivityDemo {
static class Pt {
final int x, y;
Pt(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Pt)) return false;
Pt p = (Pt) o;
return p.x == x && p.y == y;
}
@Override
public int hashCode() {
return 31 * x + y;
}
}
static class ColorPt extends Pt {
final String color;
ColorPt(int x, int y, String color) {
super(x, y);
this.color = color;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Pt)) return false;
if (!(o instanceof ColorPt)) return o.equals(this); // ignore color
return super.equals(o) && ((ColorPt) o).color.equals(color);
}
@Override
public int hashCode() {
return 31 * super.hashCode() + color.hashCode();
}
}
public static void main(String[] args) {
ColorPt red = new ColorPt(1, 2, "red");
Pt plain = new Pt(1, 2);
ColorPt blue = new ColorPt(1, 2, "blue");
System.out.println(red.equals(plain)); // true
System.out.println(plain.equals(blue)); // true
System.out.println(red.equals(blue)); // false
}
}Symmetry now holds, but transitivity is gone. The diagram above shows this exact situation.
There is no way to extend an instantiable class with a new value-bearing field and keep the contract, as long as the subclass can equal its superclass. You have three choices:
- Make the class
final, so no subclass can exist. - Compare with
getClass()instead ofinstanceof, so aColorPtnever equals aPt. This keeps all the rules but breaks substitutability. APtand a subclass instance with the same coordinates are never equal. - Use composition.
ColorPtholds aPtas a field and exposes it through anasPoint()method instead of extendingPt.
The "Equality across subclasses" chapter compares these options. For now, remember that the contract itself forces the decision.
Consistency
equals should depend only on the state that defines the object's value. Two things commonly break consistency:
- Unreliable resources.
java.net.URL.equalsmay resolve host names to IP addresses, so its answer can depend on the network and change over time. The Javadoc forURLitself warns about this. Preferjava.net.URI, which compares text components only. - Mutable state that is used as a key. Fields can change legitimately, but a hash-based collection stores the object using the state it had at insertion. Later chapters show how this loses entries.
A good habit is to compute equality only from the fields that make up the value, and never from caches, timestamps, or lazily computed data.
Non-nullity
x.equals(null) must return false, and it must never throw NullPointerException. Many people write explicit if (o == null) return false;. That check is correct but redundant if you use instanceof, because null instanceof AnyType is always false:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false; // also rejects null
Point other = (Point) o;
return x == other.x && y == other.y;
}The NPE risk comes from the opposite direction. Calling name.equals(other.name) throws if name is null. Objects.equals(name, other.name) returns true when both are null and false when only one is.
Checking a contract by hand
You can spot-check the rules with a small helper. It does not prove correctness, because it only tests the values you give it, but it catches the common slips:
import java.util.List;
public class ContractCheck {
static void check(Object x, Object y, Object z) {
System.out.println("reflexive: " + x.equals(x));
System.out.println("symmetric: " + (x.equals(y) == y.equals(x)));
System.out.println("transitive: "
+ (!(x.equals(y) && y.equals(z)) || x.equals(z)));
System.out.println("consistent: " + (x.equals(y) == x.equals(y)));
System.out.println("null-safe: " + !x.equals(null));
}
public static void main(String[] args) {
check("a", new String("a"), "a");
check(List.of(1, 2), List.of(1, 2), List.of(1, 2));
}
}Each line prints true for the JDK classes shown. The same helper, run on the ColorPt example from earlier with red, plain, and blue, would print false for the transitive line. Proper test suites for this appear in the testing chapter.
Summary of decisions
- Treat the five rules as requirements on every override, not as style advice.
- Compare only against your own class. Do not try to be equal to types you do not own.
- Do not add value fields in a subclass of a concrete class with an
instanceof-basedequals. Usefinal,getClass(), or composition. - Base
equalson stable, value-defining fields only. - Use
instanceoforObjects.equalsso thatnullnever causes an exception.
Exercise
A class Money has equals that returns true when the other object is a Money with the same amount, or when it is a BigDecimal with the same numeric value. Which contract rule does it break, and why? What change fixes it?
Show answer
It breaks symmetry. money.equals(bigDecimal) can return true, but bigDecimal.equals(money) always returns false, because BigDecimal.equals only accepts BigDecimal objects. Fix it by accepting only Money in Money.equals, and by providing an explicit conversion method such as toBigDecimal() for callers who need to compare values across types.
Exercise
In the TransitivityDemo code, red.equals(plain) and plain.equals(blue) are both true, yet red.equals(blue) is false. Name two ways to repair the design so that all five rules hold.
Show answer
Replace the instanceof checks with getClass() != o.getClass() checks so that a ColorPt never equals a Pt, or make ColorPt hold a Pt field through composition instead of extending it. Making Pt final also works only if ColorPt is removed as a subclass, so composition takes its place.