equals and hashCode: the contract maps rely on
You put a key into a HashMap, build an equal key, and get returns null. The map is fine; your class broke a two-line contract. Here is the contract, and the exact point where the map trips over it.
01 A key you cannot get back
Point says two points are equal when their coordinates are. The map holds (1, 2). You ask for (1, 2), and it is not there.
Real output on JDK 17. The two points are equal by equals, yet the map cannot find one with the other. The missing piece is the comment near the top: there is no hashCode().
02 What Object gives you by default
Every class inherits both methods from Object. The defaults are about identity: is this the very same object in memory?
| Method | Default behaviour | So two new Point(1, 2) are… |
|---|---|---|
| equals(Object o) | this == o: the same object | not equal |
| hashCode() | an identity hash, picked per object | almost always different |
In HotSpot, the identity hash is not the memory address. It is a random-looking number generated the first time something asks for it, then kept in the object’s header so it never changes. Two objects almost never get the same one.
Lost replaced equals with a field comparison but kept the identity hashCode. Now the two methods disagree: equals says the points are the same, hashCode says they are different. A HashMap asks hashCode first.
03 How a HashMap uses the two methods
get(key) does not search the map. It calls key.hashCode(), mixes the bits, and picks one bucket from them. Only the entries in that bucket are checked, first by comparing stored hashes, then with equals. So hashCode decides where to look, and equals decides which entry it is.
- just stored
- bucket picked
- empty bucket
A new HashMap with 16 buckets. Nothing is stored yet. The identity hashes below are examples; yours change every run.
Give Point a hashCode built from the same fields equals compares, and both calls land in the same bucket.
- just stored
- bucket picked
- equals says yes
- empty bucket
The same map and the same two calls, but Point now has hashCode() returning Objects.hash(x, y). Nothing is stored yet.
get, containsKey and remove miss, and a HashSet keeps duplicates.equals confirms the match.04 The contract, rule by rule
The rules are written in the Javadoc of Object. Every hash-based collection in the JDK assumes them, without checking.
| Rule | In plain words | If you break it |
|---|---|---|
| a.equals(b) ⇒ same hashCode | Equal objects hash alike | Maps and sets lose keys and keep duplicates |
| hashCode is stable | Same object, same hash, while equals’ fields stay put | A key cannot be found after it changes |
| equals is an equivalence | Reflexive, symmetric, transitive, consistent | Results depend on which side calls equals |
| x.equals(null) is false | Never true, never a crash | NullPointerException inside collection code |
| Same hash ⇏ equal | Unequal objects may share a hash | Nothing breaks; that bucket gets slower |
The rule only goes one way. Equal objects must share a hash code; objects with the same hash code need not be equal. Collisions are allowed, and the map handles them with equals.
05 Writing them so they agree
Use the same fields in both methods, and take Object as the parameter of equals. Objects.hash combines the fields with the classic multiply-by-31 recipe.
This uses an instanceof pattern, so it needs Java 16 or later. If the class is just data, a record writes both methods for you, from all its components:
final class Point {private final int x, y;// constructor, equals,// hashCode, toString...}
record Point(int x, int y) {}
- Make the fields that
equalsreadsfinal, so the hash cannot change while the object sits in a map. - Mark both methods
@Override. A typo likeequals(Point p)then fails to compile instead of silently doing nothing. - Let your IDE or a record generate them when you can. Hand-written versions drift when someone adds a field to one method and not the other.
06 When it bites
Override both or neither. A class that overrides only equals works in a List, passes every assertEquals, and then quietly loses entries the first time it is used as a HashMap key or put in a HashSet.
seen.add(p);
p.x = 5;
seen.contains(p); // falseA key that changes after it is storedThe entry stays in the bucket for the old hash. Lookups go to the bucket for the new hash, so even the same object is not found, and size() still counts it.public boolean equals(Point p)Overloading instead of overridingThis adds a second method; collections call equals(Object), which is still the identity check. A HashSet with this Point reports contains as false.Map<int[], String> mArrays as keysArrays use the identity equals and hashCode, so new int[]{1, 2} never finds another {1, 2}. Use List.of(1, 2) or a record.new BigDecimal("2.0")
.equals(new BigDecimal("2.00"))Equal values, unequal objectsThis is false, because BigDecimal.equals also compares the scale. A HashSet keeps both; a TreeSet, which uses compareTo, keeps one.public int hashCode() { return 42; }A legal but useless hashIt keeps the contract, since equal objects get equal hashes, but every key lands in one bucket and lookups slow to a crawl.