The equals and hashCode contract

Junior Always asked 7 min

On this page

The question

Why must you override hashCode() whenever you override equals()?

30-second answer

Hash-based collections find an object by hashCode() first and call equals() only inside the bucket it picks. The contract says equal objects must return equal hash codes. Override equals() alone and two equal Points keep different identity hashes, so a HashSet or HashMap looks in the wrong bucket and never finds the match. Build both from the same fields.

Understand it

Lost in a HashSet

Predict

Point overrides equals() but not hashCode(). The code calls set.add(new Point(1, 2)), then set.contains(new Point(1, 2)) with a second, equal Point.

What does set.contains(new Point(1, 2)) return?
View as text

Point overrides equals() but not hashCode(). The code calls set.add(new Point(1, 2)), then set.contains(new Point(1, 2)) with a second, equal Point. The drawing shows two Point(1, 2) objects, p1 that is added and p2 that is looked up, marked as equal, above the 16 buckets of the set. A warning says hashCode() is not overridden. The learner first predicts what contains() returns.

add() asks p1 for its hashCode(). With no override, that is the identity hash of the object, and it picks the bucket that stores p1. A badge "identity hash A" appears under p1 with an arrow to one bucket, which fills.

contains() asks the equal p2 for its hashCode(). p2 is a different object with its own identity hash, which here picks a different bucket. A badge "identity hash B" appears under p2 with an arrow to another bucket, which is empty.

That bucket holds no Point, so contains() returns false. equals() is never called, even though p1.equals(p2) is true. A failure mark reads "contains() is false".

Point overrides equals() but not hashCode(). The code calls set.add(new Point(1, 2)), then set.contains(new Point(1, 2)) with a second, equal Point. The drawing shows two Point(1, 2) objects, p1 that is added and p2 that is looked up, marked as equal, above the 16 buckets of the set. A warning says hashCode() is not overridden. The learner first predicts what contains() returns.

add() asks p1 for its hashCode(). With no override, that is the identity hash of the object, and it picks the bucket that stores p1. A badge "identity hash A" appears under p1 with an arrow to one bucket, which fills.

contains() asks the equal p2 for its hashCode(). p2 is a different object with its own identity hash, which here picks a different bucket. A badge "identity hash B" appears under p2 with an arrow to another bucket, which is empty.

That bucket holds no Point, so contains() returns false. equals() is never called, even though p1.equals(p2) is true. A failure mark reads "contains() is false".

Takeaway: Equal objects must return equal hash codes. If they do not, a HashSet searches the wrong bucket and never calls equals().

How a HashSet finds an equal Point

Step by step

set.contains(new Point(1, 2)) starts by calling hashCode() on the key. Point builds it with Objects.hash(x, y), which gives 994.

Step 1 of 5
View as text

The code is set.contains(new Point(1, 2)) on a HashSet that holds Point(1, 18) and Point(1, 2). The drawing shows the key, its hashCode(), the masking step, a row of 16 buckets and the chain of the chosen bucket.

set.contains(new Point(1, 2)) starts by calling hashCode() on the key. Point builds it with Objects.hash(x, y), which gives 994.

A HashSet keeps its elements as keys of a HashMap. The hash is spread, then masked with 15 for a 16-bucket table: bucket 2. An arrow leads to bucket 2.

Bucket 2 holds two entries. The lookup compares stored hashes first: 1010 is not 994, so that entry is skipped without calling equals(). The chain shows (1, 18) with hash 1010, marked as skipped, then (1, 2) with hash 994, marked as a hash match.

The second entry's hash matches 994, so equals() compares x and y. It returns true, and so does contains().

Without hashCode(), the equal key gets a different, identity hash. Here it lands in another bucket, equals() never runs, and contains() returns false. The stored (1, 2) sits in one bucket while the arrow points at an empty one.

The code is set.contains(new Point(1, 2)) on a HashSet that holds Point(1, 18) and Point(1, 2). The drawing shows the key, its hashCode(), the masking step, a row of 16 buckets and the chain of the chosen bucket.

set.contains(new Point(1, 2)) starts by calling hashCode() on the key. Point builds it with Objects.hash(x, y), which gives 994.

A HashSet keeps its elements as keys of a HashMap. The hash is spread, then masked with 15 for a 16-bucket table: bucket 2. An arrow leads to bucket 2.

Bucket 2 holds two entries. The lookup compares stored hashes first: 1010 is not 994, so that entry is skipped without calling equals(). The chain shows (1, 18) with hash 1010, marked as skipped, then (1, 2) with hash 994, marked as a hash match.

The second entry's hash matches 994, so equals() compares x and y. It returns true, and so does contains().

Without hashCode(), the equal key gets a different, identity hash. Here it lands in another bucket, equals() never runs, and contains() returns false. The stored (1, 2) sits in one bucket while the arrow points at an empty one.

Takeaway: A lookup trusts hashCode() to pick the bucket and uses equals() only inside it. Equal objects with different hashes are never compared.

The equals and hashCode contractWhen a equals b, their hash codes must be the same. The reverse does not hold. The same hash code can belong to objects that are equal, or to objects that are not, a collision such as the strings Aa and BB, which both hash to 2112.must givecan come fromcan come froma.equals(b) is truethe samehashCode()equal objectsunequal objects: Aaand BB, both 2112
The equals and hashCode contractWhen a equals b, their hash codes must be the same. The reverse does not hold. The same hash code can belong to objects that are equal, or to objects that are not, a collision such as the strings Aa and BB, which both hash to 2112.must givecan come fromcan come froma.equals(b) is truethe samehashCode()equal objectsunequal objects: Aaand BB, both 2112
The contract runs one way: equal objects need equal hashes, not the reverse

In code

class Point {
    private final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }

    @Override public boolean equals(Object o) {
        return o instanceof Point p && x == p.x && y == p.y;
    }
    @Override public int hashCode() { return Objects.hash(x, y); }
}

Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
set.contains(new Point(1, 2));   // true; false if hashCode() is removed
Build equals() and hashCode() from the same fields
class MutablePoint {
    int x, y;
    MutablePoint(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        return o instanceof MutablePoint p && x == p.x && y == p.y;
    }
    @Override public int hashCode() { return Objects.hash(x, y); }
}

Set<MutablePoint> set = new HashSet<>();
MutablePoint p = new MutablePoint(1, 2);
set.add(p);
 Wrong p.x = 5;              // changes the hash: p now sits in the wrong bucket
set.contains(p);      // false
set.remove(p);        // false: p cannot be removed
set.size();           // 1
A key changed after add() is stuck in the set
How set.contains finds an equal PointThe HashSet asks the key p for its hashCode and gets 994. It masks the hash to bucket 2 of the table. In that bucket it finds a stored entry with the same hash, so it calls equals on p, which returns true.bucket 2key pHashSethashCode()994994 & 15 = 2entry, hash 994equals(entry)true
How set.contains finds an equal PointThe HashSet asks the key p for its hashCode and gets 994. It masks the hash to bucket 2 of the table. In that bucket it finds a stored entry with the same hash, so it calls equals on p, which returns true.bucket 2key pHashSethashCode()994994 & 15 = 2entry, hash 994equals(entry)true
set.contains(p): hashCode, then the bucket, then equals
record Point(int x, int y) {}

Set<Point> set = new HashSet<>(List.of(new Point(1, 2)));
boolean found = set.contains(new Point(1, 2));   // true, with no equals or hashCode written
A record derives equals() and hashCode() from its components

Solve it

Why does list.contains() depend on which point you ask about?

ColorPoint extends Point and overrides equals to compare the color too. With p = new Point(1, 2) and cp = new ColorPoint(1, 2, RED), p.equals(cp) is true but cp.equals(p) is false, so collections give different answers depending on order. Explain and fix it.

  1. Check the contract. equals must be reflexive, symmetric, transitive and consistent, and return false for null. Run both directions.
  2. Find the asymmetry. Point.equals uses instanceof Point, which accepts a ColorPoint and ignores color. ColorPoint.equals rejects a plain Point.
  3. Know why patching fails. No equals can add a field in a subclass and keep the contract with the parent. Ignoring color in one direction breaks transitivity instead.
  4. Fix with composition. ColorPoint has a Point instead of being one. Each class compares only its own kind.
  5. Check. Both directions agree, and hashCode uses the same fields as equals.
record Point(int x, int y) {}                 // final, value-based equals and hashCode

record ColorPoint(Point point, Color color) { // has a Point, is not one
    Point asPoint() { return point; }
}

Point p = new Point(1, 2);
ColorPoint cp = new ColorPoint(p, Color.RED);
boolean a = p.equals(cp);                     // false
boolean b = cp.equals(p);                     // false: symmetric
boolean c = p.equals(cp.asPoint());           // true: compare like with like
Composition keeps equals symmetric

How to answer

  • The contract: if a.equals(b) is true, a.hashCode() must equal b.hashCode().
  • The reverse does not hold: equal hashes can belong to unequal objects, a collision.
  • HashMap and HashSet use hashCode() to pick a bucket, then equals() inside it.
  • Compute both from the same fields, for example with Objects.hash(x, y).
  • A record generates both from its components.

Common mistakes

  • Saying every object needs a unique hash code; collisions are allowed, only equal objects must share one.
  • Using a field in hashCode() that equals() ignores, so two equal objects get different hashes.

Follow-up questions

What breaks in a HashSet if you override equals() but not hashCode()?

Lookups. Each Point keeps the identity hash it inherits from Object, so an equal Point has a different hash and is searched for in the wrong place: contains() returns false, remove() removes nothing, and add() accepts the duplicate. Nothing throws; the set silently holds two equal elements. HashMap keys break the same way.

  • contains() and remove() miss elements that are equal to one in the set.
  • add() accepts an equal element again, so size() counts it twice.
  • No exception is thrown; the bug shows up as wrong results.
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
set.contains(new Point(1, 2)); // false without hashCode()
set.add(new Point(1, 2));      // true: size() is now 2

See it in the infographic: Lost in a HashSet See it in the infographic: How a HashSet finds an equal Point

What rules must an equals() implementation follow?

Object's documentation lists five. Reflexive: x.equals(x) is true. Symmetric: x.equals(y) is true exactly when y.equals(x) is. Transitive: if x equals y and y equals z, x equals z. Consistent: repeated calls agree while the compared fields do not change. And x.equals(null) is false. hashCode() must agree with it.

  • Reflexive, symmetric, transitive, consistent, and false for null.
  • Take Object as the parameter; equals(Point) is an overload that collections never call.
  • Compare the same fields that hashCode() uses.

See it in the infographic: How a HashSet finds an equal Point

What happens if you change a field used by hashCode() after adding the object to a HashSet?

The object stays in the bucket chosen from its old hash. contains() and remove() compute the new hash, look in another bucket and miss, so the element is stuck: you cannot find or remove it, but size() still counts it. Keep key fields immutable, or remove the object, change it, then add it again.

  • The bucket is chosen from the hash at the time of add().
  • contains() and remove() use the current hash and miss.
  • Prefer immutable keys such as String, records and classes with final fields.
MutablePoint p = new MutablePoint(1, 2);
set.add(p);
p.x = 5;
set.contains(p); // false
set.size();      // 1

See it in the infographic: How a HashSet finds an equal Point

How do records and Lombok help with equals() and hashCode()?

A record generates equals(), hashCode() and toString() from all its components, so record Point(int x, int y) gets value equality for free. Lombok's @EqualsAndHashCode, also part of @Data, generates both from the class's fields at compile time. Both remove hand-written mistakes, but you still decide what defines equality, and a mutable field still breaks hash-based collections.

  • A record compares all its components, and its fields are final.
  • Lombok's @EqualsAndHashCode and @Data generate both methods from the fields.
  • A record with a mutable component, such as a List, can still change its hash.
record Point(int x, int y) {}
new Point(1, 2).equals(new Point(1, 2)); // true

See it in the infographic: How a HashSet finds an equal Point

If two objects have the same hashCode(), are they equal?

Not necessarily. Equal objects must have equal hashes, but not the other way round: an int has about 4 billion values, and objects can have far more states, so collisions are unavoidable. "Aa" and "BB" both hash to 2112. A HashMap keeps colliding keys in the same bucket and uses equals() to tell them apart.

  • Equal objects imply equal hashes; equal hashes do not imply equal objects.
  • Colliding keys share a bucket, and equals() decides which entry matches.
  • A good hashCode() spreads values so collisions stay rare.
boolean strings = "Aa".hashCode() == "BB".hashCode();       // true: both 2112
boolean points = Objects.hash(0, 33) == Objects.hash(1, 2); // true: both 994

See it in the infographic: How a HashSet finds an equal Point

Is a hashCode() that returns a constant legal?

Yes. It keeps the contract, because equal objects always get equal hashes. But every element lands in the same bucket, so a lookup has to search that one crowded bucket instead of jumping straight to the right entry, and HashMap loses its constant-time lookups.

Should equals() use getClass() or instanceof?

instanceof lets a subclass equal its parent, which breaks symmetry once a subclass adds a field: a Point equals a ColorPoint, but not the other way round. getClass() only matches the exact class, so it stays symmetric, but a subclass never equals its parent. A final class or a record avoids the choice.

Why does a HashMap compare hashes before calling equals()?

Each entry stores its key's hash, and comparing two ints is cheap. Different hashes prove the keys are not equal, so in a crowded bucket the lookup skips every entry whose hash differs and calls the costlier equals() only on a hash match.

Check yourself

1. Point overrides equals() but not hashCode(). What does this print?
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
System.out.println(set.contains(new Point(1, 2)));
Show answers
  • true: Incorrect. The equal Point has a different identity hash, so the lookup never reaches the stored one.
  • false: Correct. Without hashCode(), the equal Point is searched for in the wrong bucket.
  • It throws an exception: Incorrect. Nothing checks that equals() and hashCode() agree; the lookup just misses.
  • It does not compile: Incorrect. Overriding equals() alone compiles; the contract is not checked by the compiler.
2. Which statements does the equals() and hashCode() contract require?Choose 2
Show answers
  • If a.equals(b) is true, a.hashCode() equals b.hashCode(): Correct. This is the rule hash-based collections rely on to find equal objects.
  • If a.hashCode() equals b.hashCode(), a.equals(b) is true: Incorrect. Collisions are allowed; "Aa" and "BB" share a hash but are not equal.
  • Objects that are not equal must have different hash codes: Incorrect. Distinct hashes help performance, but the contract does not require them.
  • hashCode() returns the same value while the fields equals() uses do not change: Correct. A lookup recomputes the hash, so it must not drift for an unchanged object.
3. MutablePoint builds equals() and hashCode() from x and y, and x is not final. What does the last line print?
MutablePoint p = new MutablePoint(1, 2);
Set<MutablePoint> set = new HashSet<>();
set.add(p);
p.x = 5;
System.out.println(set.contains(p) + " " + set.size());
Show answers
  • true 1: Incorrect. The lookup uses p's new hash, which picks another bucket than the one p sits in.
  • false 1: Correct. p stays in the bucket of its old hash, so contains() misses but size() still counts it.
  • false 0: Incorrect. Changing a field does not remove the element; it is stuck in the set.
  • true 2: Incorrect. Nothing adds a second element; only a field changed.