The Plain Picture#
A library files books in numbered bins by a quick rule — say, the first letter of the title. To check "do we have Biology Basics?", the librarian goes straight to bin B and compares titles only there. If two copies of the same book were somehow filed into different bins, the librarian would look in one bin and wrongly say "we don't have it".
The Real Names#
equalsdecides whether two objects are logically equal (Classes, Objects and Memory Ch 9).hashCodereturns anint"bin number" for an object. Hash-based collections —HashMap,HashSet(Collections, From the Inside) — use it to decide which bin to look in, and only then callequalswithin that bin.The contract:
If
a.equals(b)is true, thena.hashCode() == b.hashCode()must be true. (Equal objects must go in the same bin.)Unequal objects may share a hash code (a collision — allowed, just slower).
hashCodemust stay the same while the object's relevant fields don't change.
equalsitself must be: reflexive (a.equals(a)), symmetric (a.equals(b)⇔b.equals(a)), transitive, consistent, anda.equals(null)must befalse.
So: whenever you override equals, you must override hashCode too.
Under the Hood — breaking it, then fixing it#
A grid position class, overriding only equals:
class PointBroken {
final int x, y;
PointBroken(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true; // same object → equal (fast path)
if (!(o instanceof PointBroken p)) return false; // null or a different type → not equal
return x == p.x && y == p.y; // compare the fields that define equality
}
// no hashCode! → inherits Object's, which is based on identity
}And a correct one:
class PointGood {
...same equals...
@Override public int hashCode() { return Objects.hash(x, y); } // built from the SAME fields as equals
}Set<PointBroken> s1 = new HashSet<>();
s1.add(new PointBroken(1, 2));
Set<PointGood> s2 = new HashSet<>();
s2.add(new PointGood(1, 2));
System.out.println(
new PointBroken(1, 2).equals(new PointBroken(1, 2)) +
" " +
s1.contains(new PointBroken(1, 2)) +
" " +
s2.contains(new PointGood(1, 2))
);
// true false trueequals says the two broken points are equal — yet the set says it doesn't contain one. The two objects got different identity-based
hash codes, so contains looked in the wrong bin and never even called equals. This exact bug happens in DSA whenever you put your own
class (a grid cell, a state) into a HashSet or use it as a HashMap key — the classic example is "visited" sets in BFS
(Graphs I (coming soon)).
Rules of thumb:
Build
equalsandhashCodefrom exactly the same fields.Use
Objects.hash(...)andObjects.equals(a, b)(null-safe) — or let a record (Ch 12) or your IDE generate them.Prefer immutable keys (Classes, Objects and Memory Ch 5). If you change a field of an object after putting it in a
HashSet, its hash changes and the set can no longer find it.
Check yourself
4 questionsState the equals/hashCode contract.
Show answerHide answer
Equal objects (per equals) must have equal hash codes; equal hash codes don't require equal objects; the hash must be stable while the
fields don't change.
Why did s1.contains(...) return false even though equals returned true?
Show answerHide answer
Without an overridden hashCode, the two equal points had different identity hash codes, so the set looked in a different bucket and
never compared them with equals.
Why must hash-map keys not change while in the map?
Show answerHide answer
Their hash code would change, so the map would look in the wrong bucket and "lose" them.
What's a hash collision, and is it a bug?
Show answerHide answer
Two unequal objects with the same hash code; it's allowed and handled, just slower when frequent.