Lesson · The Object Class & Core Contracts
The hashCode contract: equal objects, equal hashes
16 min readThe hashCode() Contract
Hash structures find objects in two moves: the hash picks the bucket, equals confirms the match. Equal objects with different hashes are lost, and a key that mutates inside the map loses itself.
The map that cannot find its own key
equals was carefully written; the map still answers null:
class Point { int x, y; @Override public boolean equals(Object o) { ... } // value equality: done // hashCode: not overridden. The other half is missing. } Map<Point, String> map = new HashMap<>(); map.put(new Point(2, 3), "here"); System.out.println(map.get(new Point(2, 3))); // null?
Predict: two points, equal by every field, both in the map's world; the lookup still misses. Hash structures do not search everything: they compute a number to find the right shelf, then use equals there. The missing half is hashCode.
Two moves: hash first, equals second
Picture the map as shelves (buckets). Storage and lookup both go through the same two moves:
- Compute
hashCode(); the number picks the shelf.Point(2, 3)hashes to 65, and 65 % 4 shelves = shelf 1. putplaces the entry on that shelf;getin the same situation lands on the same shelf.- Within the shelf,
equalsmakes the final call: several objects may share a shelf, and equals tells them apart. - Equal objects must produce the same hash, or the second move never happens: the lookup checks a shelf the entry never sat on.
Collisions are normal; disagreement is fatal. Different objects sharing a shelf merely costs a little speed; equal objects with different shelves loses data silently, which is the failure this lesson exists to prevent.
Hash shelves · hash first, equals second
The map, drawn as four shelves
shelf 0
empty
shelf 1
shelf 2
empty
shelf 3
empty
hash(Point(2,3)) = 65 → shelf 1
put(key): hashCode() returns 65, and 65 % 4 shelves is shelf 1. The entry is shelved there, complete with its value. Nobody looked at equals yet.
Writing hashCode that agrees with equals
The contract in one line: objects that are equal must return the same hash, and the hash must stay stable while the object is in use. The recipe:
@Override public int hashCode() { return Objects.hash(x, y); // exactly the fields equals compares, in any order }
- Same fields as equals: a field equals ignores must not reach the hash, or two equal objects disagree; a field equals uses must be in it, for the same reason.
- Stable inputs: final fields are ideal. The contract technically holds while state is unchanged; collections rely on the change never happening while the object is stored.
- Any consistent formula works:
Objects.hash(...)(convenient, slightly slower) or the classic31 * result + field; both are fine, constant quality matters more than cleverness. - Never a constant:
return 1;is legal and technically consistent, and turns every bucket into one long shelf; the map degrades to a linked list.
equals and hashCode are one design decision in two methods. Same fields, same stability, same commit; the compiler will not connect them, and no test fails until a collection is involved.
The key that mutates inside the map
The second promise, consistency, has a physical consequence: an object's hash is frozen into the map's structure the moment it is stored.
put(key, "here")computes the hash and shelves the entry: shelf 1, key's hash 65.- Someone changes a compared field:
key.x = 9. The object's hash is now 282: shelf 2. get(key)recomputes the hash: shelf 2. Only the key's current hash is consulted for the initial landing.- Shelf 2 does not contain the entry; it is still on shelf 1, under the old hash. The map answers null, holding the entry and unable to find it, in the same breath.
Verified with a real HashMap: same key object, one field changed, lookup went from here to null. If keys must mutate, make the compared fields immutable (or use an immutable ID for equality), and the trap disappears.
The hashCode playbook
Shipping hash-safe classes, in order:
- Override equals first, then write hashCode from the same field list, in the same commit.
- Reach for
Objects.hash(fields...)for convenience or the31 *loop for control; either is correct when the field lists match. - Prefer immutable compared fields; if a field must change, keep it out of equals and hashCode (and document why).
- Test with the round trip:
map.put(key, v)thenmap.get(equalCopy); one line catches both the missing hashCode and the mismatched field list. - When debugging a missing lookup, print
hashCode()of both sides plusequals(); the pair of numbers explains the shelf mismatch instantly.
One number out, one shelf in, equals at the end. With equal hashes for equal objects and stable fields, hash structures are exact; every failure you will ever see is one of those two promises bent.
Equality is two methods; collections trust the pair
hashCode picks the shelf and equals confirms the match, so equal objects must share a stable hash. Reuse the same field list as equals, keep those fields immutable while stored, and a HashMap or HashSet behaves exactly. Mutate a compared field inside the map and the entry becomes present and unreachable at once.
Interview angles
Why must equal objects return equal hash codes?+
Because hash structures use the hash to choose where to look before equals can run. Equal objects with different hashes are stored on shelves their own lookups never visit.
HashMap (and HashSet, LinkedHashMap, ConcurrentHashMap and friends) resolve in two moves: hash to a bucket, then equals within the bucket. Break the pair and only collections notice, which is how the bug ships.
map.put(new Point(2, 3), "here"); map.get(new Point(2, 3)); // null until hashCode agrees with equals
Common misconception: That hashCode is a performance hint. It decides correctness of the initial search; collisions cost time, mismatches cost answers.
Follow-up: What is the one line test that catches it before production?
What happens when equals is overridden but hashCode is not?+
Objects that are equal by value get different identity-based hashes and land on different shelves; lookups, updates and removals in hash structures start missing.
The failure is asymmetric and quiet: the list-based operations still work (they compare each element with equals), which makes the bug look random until the collection is a map or set. Verified: the map returned null for an equal key.
// equals overridden, hashCode forgotten: map.get(new Point(2, 3)); // null, silently
Common misconception: That HashSet will 'just scan everything' as a safety net. It computes a hash first by design; safety nets would erase the performance the structure exists for.
Follow-up: Where would the same class still behave correctly?
How do you write a good hashCode?+
Use the same fields as equals, combine them with Objects.hash or the 31-multiplier loop, and keep those fields stable while the object is stored in a structure.
Consistency matters, not sophistication: the same inputs must give the same number every call, and the numbers must spread across buckets. A constant hash is legal and terrible: one shelf for every object.
@Override public int hashCode() { return Objects.hash(x, y); // matches equals exactly }
Common misconception: That a 'random-looking' formula is better. Fresh randomness per call breaks the contract outright; stable spread is the goal.
Follow-up: What does a constant hashCode turn a HashMap into, performance-wise?
What breaks when a key mutates inside a HashMap?+
Its hash changes, so lookups compute a different shelf than the one the entry sits on: the map holds the entry and returns null for its own key, exactly as verified in this lesson.
Removal misses too, and the entry only becomes findable again if the field is restored to its stored value. The cure is design: immutable keys, or equality computed from an immutable ID field.
map.put(key, "here"); key.x = 9; map.get(key); // null: the entry is on the old shelf
Common misconception: That the map is corrupted. The map is fine; the contract was changed under it. Restore the field and the entry is found again, which is the whole proof.
Follow-up: Which Java types are safe map keys by construction?
What makes a good map key in the first place?+
Immutable compared fields, ideally final, and a type whose value equality is the meaning. String, Integer, enums, records and well-designed value classes all qualify.
Immutable keys freeze their hash at construction, so the stored shelf stays the right shelf forever. Records get equals and hashCode from their components automatically, which is why they make excellent keys with zero boilerplate.
record Point(int x, int y) { } // equals + hashCode generated, immutable Map<Point, String> map = new HashMap<>();
Common misconception: That mutability is fine as long as the compared fields 'usually' stay still. Collections need guarantees, not habits.
Follow-up: What does a record's generated hashCode use?