BackendBench
Coffee
Spot the Bug #10

The equals that is not an override

A hard Java puzzle in the equality and identity family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

hardEquality and identitybuggy line: 6

Highlighted: line 6. Play this one as a puzzle without the answer.

What is wrong

The parameter type is Money, not Object, so this method overloads equals instead of overriding it. Collections call equals(Object), which is still the identity version, so contains returns false. Adding @Override would have caught it at compile time.

The fix

@Override public boolean equals(Object o) { return o instanceof Money m && m.cents == cents; }

How to avoid it next time

Put @Override on every method you intend to override. The compiler then rejects a wrong signature.

Want the background? Read equals() and hashCode() in the Java concepts library.

About equality and identity

In Java == compares primitive values but only compares references for objects. Strings, boxed numbers and enums behave differently, and a class that overrides equals without hashCode quietly breaks every hash-based collection.

In code review: Whenever you see == between two objects, stop and ask whether identity was really intended. Use equals or Objects.equals, and look for equals and hashCode written as a pair.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #9#11 โ†’

Frequently asked questions

What is the bug in "The equals that is not an override"?

The parameter type is Money, not Object, so this method overloads equals instead of overriding it. Collections call equals(Object), which is still the identity version, so contains returns false. Adding @Override would have caught it at compile time. The faulty line is line 6: public boolean equals(Money other) {

How do I fix it?

Replace it with: @Override public boolean equals(Object o) { return o instanceof Money m && m.cents == cents; }. Put @Override on every method you intend to override. The compiler then rejects a wrong signature.

How do I catch equality and identity in code review?

Whenever you see == between two objects, stop and ask whether identity was really intended. Use equals or Objects.equals, and look for equals and hashCode written as a pair.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need