The duplicate that the set keeps
A medium 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.
Highlighted: line 6. Play this one as a puzzle without the answer.
What is wrong
equals says two points with the same coordinates are equal, but hashCode is still the identity-based default, so equal objects land in different buckets. HashSet.contains usually returns false. The contract requires equal objects to have equal hash codes.
The fix
How to avoid it next time
Always override equals and hashCode together. Records and Lombok @EqualsAndHashCode generate both for you.
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
Frequently asked questions
What is the bug in "The duplicate that the set keeps"?
equals says two points with the same coordinates are equal, but hashCode is still the identity-based default, so equal objects land in different buckets. HashSet.contains usually returns false. The contract requires equal objects to have equal hash codes. The faulty line is line 6: @Override
How do I fix it?
Replace it with: public int hashCode() { return java.util.Objects.hash(x, y); }. Always override equals and hashCode together. Records and Lombok @EqualsAndHashCode generate both for you.
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.