Lesson · The Object Class & Core Contracts
The equals contract: five promises your equals must keep
16 min readThe equals() Contract
Reflexive, symmetric, transitive, consistent and null-safe: the promises equals makes to every collection and every caller. The getClass versus instanceof choice is where symmetry is won or lost.
The list that cannot find its own element
An element is added, an identical one is searched for, and the list swears it was never there:
List<Point> points = new ArrayList<>(); points.add(new Point(2, 3)); System.out.println(points.contains(new Point(2, 3))); // false? // Point never overrode equals, so equality is still identity System.out.println(points.get(0) == new Point(2, 3)); // false: different objects
Predict: contains compares with equals, and the inherited equals asks 'same object?', not 'same data?'. Every lookup tool in Java (contains, remove, indexOf, Map keys, Set dedupe) leans on equals; the contract below is what makes those leanings safe.
The five promises
The contract is short, rigid, and each promise has a famous way to break it:
| Promise | Means | Broken by |
|---|---|---|
| Reflexive | x.equals(x) is always true | Clumsy early returns; rare but real |
| Symmetric | x.equals(y) and y.equals(x) agree | Point accepting a ColorPoint while ColorPoint rejects Point |
| Transitive | If x=y and y=z then x=z | Subclasses that each compare differently with the other |
| Consistent | Repeated calls agree while state is unchanged | Time-dependent or random answers; mutable comparisons |
| Non-null | x.equals(null) returns false, never throws | A cast or field dereference before the null check |
The contract is about predictability, not preference. It does not say what equal means for your type; it says the answer must behave like a proper comparison, because collections, deduplication and remove all vote with it.
Contract tester · five promises, four defendants
pick a defendantThe implementation
reflexive
x.equals(x) is true: an object is itself.
symmetric
Identity agrees with itself from both sides.
transitive
Same-object chains hold trivially.
consistent
An object never changes which object it is.
non-null
Returns false for null, as inherited.
What callers experience
Legal, but it answers 'same object?' while callers asked 'same data?' : points.contains(new Point(2, 3)) returns false.
The asymmetry and the NullPointerException verdicts were executed with javac and java; both messages are real output.
The recipe for writing it
Five guard lines and a field comparison, in this order:
@Override public boolean equals(Object other) { if (this == other) return true; // 1. reflexive shortcut if (other == null) return false; // 2. non-null promise if (getClass() != other.getClass()) return false; // 3. same class, strictly Point p = (Point) other; // 4. safe now return x == p.x && y == p.y; // 5. compare the value fields }
- The
this == othershortcut satisfies reflexivity and speeds up common cases. - The null check earns the non-null promise: false, never a NullPointerException.
- The class check is the symmetry gate; the alternatives get their own table below.
- Only now is the cast safe, and only value fields (not IDs of objects that stand for themselves) belong in the comparison.
@Overrideguards the whole thing: a wrong parameter type would otherwise create an overload nobody calls.
Compare reference fields with care. Objects.equals(a.field, b.field) handles nulls; primitives compare with == except double/float (NaN argues with itself; use Double.compare). The utilities get their own lesson.
getClass or instanceof: where symmetry is decided
Both checks stop most impostors; they differ exactly at subclassing:
| Check | Meaning | Trade |
|---|---|---|
getClass() != other.getClass() | Equal only to objects of the very same class | Symmetry safe by construction; a subclass is never equal to the parent |
other instanceof Point | Equal to the parent and to subclasses that pass the same test | Subclass-friendly; opens the ColorPoint asymmetry unless the class is final |
- Default to `getClass()` for value classes. It cannot be defeated by a subclass you have not met yet.
- Choose `instanceof` only when subclasses are meant to be equal, and then either make the class
final(the check becomes equivalent) or design the subclasses to complement each other's equality. - The verified failure of the careless choice:
p.equals(cp)answeredtruewhilecp.equals(p)answeredfalse: symmetry broken, and collections now disagree with themselves depending on who asks.
Whichever check wins, document it. The next authors cannot see your intent; one sentence in the Javadoc saves them from 'improving' the check into a symmetry bug.
The equals playbook
Shipping equality, in order:
- Decide the meaning first: identity (services, entities: usually leave the default) or value (records, points, money: override).
- Write the five-line recipe with
@Overrideand the class check of your choice. - Pair it with
hashCodein the same commit; the next lesson is the proof of why. - Keep compared fields stable: prefer final fields; a mutable field makes objects change their own answers mid-conversation.
- Test with a container: add one instance, then
containsan equal copy; that single test catches the near-miss overload and most symmetry slips.
One method, five promises, every collection watching. The recipe is settled engineering: guard clauses in order, value fields compared, hashCode beside it, and one container test before shipping.
equals is a contract with collections, not a style choice
Reflexive, symmetric, transitive, consistent and null-safe: break any promise and lookups, deduplication and removal start answering by chance. The recipe is mechanical (shortcut, null check, class check, cast, compare), and the one real decision is getClass versus instanceof for the class check, which is where symmetry lives.
Interview angles
What are the promises of the equals contract?+
Reflexive (x.equals(x)), symmetric (x and y agree), transitive (equals chains hold), consistent (same answer while state is unchanged) and null-safe (false, never an exception).
Each has a classic breaker: the ColorPoint pair kills symmetry, careless subclasses kill transitivity, time-dependent answers kill consistency, and a cast before the null check kills the non-null promise with a NullPointerException.
p.equals(cp); // true: Point accepts the ColorPoint cp.equals(p); // false: ColorPoint demands the extra field // symmetric equality just broke
Common misconception: That the contract is a style guide. Containers execute it: a HashSet or HashMap is only as correct as the equals and hashCode it is given.
Follow-up: Which promise does a mutable compared field endanger?
getClass or instanceof in equals: which do you choose?+
getClass for value classes: strict same-class equality, symmetry safe by construction. instanceof only when subclasses are designed to be equal, and preferably with the class final.
instanceof opens the door to subclass equality; a subclass that adds state breaks symmetry unless it complements the parent's test exactly. getClass refuses the whole problem by definition and costs only the parent-first equality.
if (getClass() != other.getClass()) return false; // strict, symmetry-safe if (!(other instanceof Point)) return false; // open, needs care
Common misconception: That instanceof is 'more modern'. The choice is about extensibility and symmetry, not age; the verified ColorPoint example fails with the careless variant.
Follow-up: What makes instanceof safe when the class is final?
Write equals from memory: what is the recipe?+
Shortcut (this == other), null check, class check, cast, compare value fields, all under @Override.
The order matters: the shortcut gives reflexivity and speed, the checks make the cast safe, and @Override turns a near-miss parameter type into a compile error. Reference fields compare via Objects.equals; doubles via Double.compare.
@Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; var p = (Point) other; return x == p.x && y == p.y; }
Common misconception: That equals(Point) is close enough to equals(Object). It is a different method; collections call the Object signature and never touch the overload.
Follow-up: Which single test catches that near miss?
What actually breaks in a program when symmetry fails?+
Answers depend on which object asks the question: contains succeeds one way and fails the other, remove misses, and two collections can disagree about the same pair.
list.contains(cp) may be true while list.contains(p) is false for the very same contents, because List calls the element's equals with its own argument order. Debugging becomes order-of-operations archaeology, which is why the contract exists.
points.contains(p); // asks p.equals(each element) points.contains(cp); // asks cp.equals(each element): a different question now
Common misconception: That asymmetric equals is a harmless edge case. It makes behaviour depend on operand order, the definition of a heisenbug.
Follow-up: How does getClass() make the failure impossible?
Should equals compare mutable fields?+
Prefer stable fields, ideally final ones. A field that changes while the object sits in a hash structure makes the object unable to find its own entry, and equals answers drift while state changes.
The consistency promise is conditional: while state is unchanged, answers must agree. Mutability does not break equals by itself; it breaks the assumption that an object's identity of value holds still, which collections rely on even more heavily through hashCode.
set.add(point); point.x = 9; // the object just changed its own answer set.contains(point); // likely false: see the next lesson for the why
Common misconception: That adding mutation to equals is fine as long as the class still 'works'. It works until the object enters a hash structure, which is exactly where such objects end up.
Follow-up: Which method does the mutation actually blind: equals or hashCode?