Skip to content

equals and hashCode: the contract maps rely on

Working knowledgeConcept

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.

Lost.java
import java.util.HashMap;
import java.util.Map;
public class Lost {
static final class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
// no hashCode()
Shell
$ javac Lost.java && java Lost
true
null
false

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?

The defaults in java.lang.Object
MethodDefault behaviourSo two new Point(1, 2) are…
equals(Object o)this == o: the same objectnot equal
hashCode()an identity hash, picked per objectalmost 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.

Without hashCode: get looks in the wrong bucket
Step 1 of 4
equals calls 0
HashMap buckets · 16
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
What the map did
Empty
  • 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.

— bucket

Give Point a hashCode built from the same fields equals compares, and both calls land in the same bucket.

With hashCode: same bucket, then equals
Step 1 of 4
equals calls 0
HashMap buckets · 16
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
What the map did
Empty
  • 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.

— bucket
Only equalsWrong bucketEqual keys hash to unrelated buckets, so get, containsKey and remove miss, and a HashSet keeps duplicates.
equals and hashCodeRight bucket, one compareEqual keys share a hash, so they meet in one bucket, where 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.

The equals and hashCode contract
RuleIn plain wordsIf you break it
a.equals(b) ⇒ same hashCodeEqual objects hash alikeMaps and sets lose keys and keep duplicates
hashCode is stableSame object, same hash, while equals’ fields stay putA key cannot be found after it changes
equals is an equivalenceReflexive, symmetric, transitive, consistentResults depend on which side calls equals
x.equals(null) is falseNever true, never a crashNullPointerException inside collection code
Same hash ⇏ equalUnequal objects may share a hashNothing 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.

Point.java
import java.util.Objects;
final class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {

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:

Hand-written
final class Point {
private final int x, y;
// constructor, equals,
// hashCode, toString...
}
Record (Java 16+)
record Point(int x, int y) {}
  • Make the fields that equals reads final, so the hash cannot change while the object sits in a map.
  • Mark both methods @Override. A typo like equals(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.

07 Check yourself

Question

A class overrides hashCode from its fields but not equals. You add new P(1, 2) to a HashSet, then call contains(new P(1, 2)). What do you get?

Question

Every Point returns 42 from hashCode, and equals compares fields. Is that correct?

Question

A mutable Point is in a HashSet. You change its x, then call contains with the same object. What happens?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?