Why must a Java class that overrides equals() also override hashCode(), and what goes wrong otherwise?
A hash table looks for a key only in the cell given by its hash code. If two equal objects have different hash codes, the lookup searches the wrong cell and reports the key missing.
* equals would say the keys match, but get never gets to call it: it is looking in the wrong bucket. *
The contract from the Javadoc of Object: equal objects must have equal hash codes. The reverse is not required; unequal objects may share a hash code (that is just a collision).
Object's default hashCode() is derived from object identity, so two separately created objects almost always get different codes. A class that defines equality by content (two Point(1, 2) objects are equal) but keeps the default hashCode() breaks the contract:
map.put(new Point(1, 2), "A");
map.get(new Point(1, 2)); // null: hashed to a different bucket
set.add(new Point(1, 2));
set.add(new Point(1, 2)); // set now holds two "equal" points
No exception is thrown; the map just behaves as if the key were missing. The fix is to compute hashCode() from exactly the fields equals() compares, e.g. return Objects.hash(x, y);. Java records generate both consistently.
Gotcha: a key must not change its hash-relevant fields while it is in a map. The entry stays in the old bucket, and lookups compute the new one.
Go deeper:
Java Object.hashCode() โ the general contract linking
equalsandhashCode.