Skip to main content
PreparationZone Logo
PrepZone

equals, hashCode and the Object Contract

The contract that makes HashMap work, and exactly what breaks when you implement only half of it.

Pass checkpoint below

Read these first

Why this matters

  • This is the single most consequential contract in the Java standard library: HashMap, HashSet, Collectors.groupingBy and distinct-value logic all depend on it.
  • The failure is silent. Nothing throws; an object simply vanishes from a set it is demonstrably inside.
  • Almost every interview that touches collections works its way to this question.
table — array of buckets
bucket 0empty
bucket 1"asha" → 30
bucket 5 — collision chain
"ravi" → 24next →
"neha" → 29next → null
bucket 9 — treeified
Red-black treeMore than 8 entries: lookup becomes O(log n)

Bucket index comes from the key's hash, not its insertion order — which is why HashMap iteration has no predictable sequence.

The hash picks a bucket. Keys that land in the same bucket form a short list, and once a bucket grows past eight entries it becomes a balanced tree so lookups stay fast.

What Object gives every class

Every class inherits eleven methods from Object. Five matter day to day.

  • equals(Object) — reference identity by default, which is rarely the comparison you want.
  • hashCode() — an int derived from the object's identity by default.
  • toString() — class name plus a hexadecimal identity hash by default, which is useless in a log.
  • getClass() — the run-time class, and final so it cannot lie.
  • clone() — a shallow field copy, protected, and covered in the next article.

The remaining ones — wait, notify, notifyAll, finalize — belong to concurrency and the deprecated finalisation mechanism, both covered later.

The default equals is identity

Java
Loading compiler…

Object.equals is literally this == other. For a value type like Point, where two instances with the same coordinates should be interchangeable, that is wrong and must be overridden.

The contract

equals must satisfy five properties. They sound academic until one is broken.

  • Reflexive — x.equals(x) is true.
  • Symmetric — if x.equals(y) then y.equals(x). Broken most often by comparing across types.
  • Transitive — if x.equals(y) and y.equals(z) then x.equals(z).
  • Consistent — repeated calls give the same answer while neither object changes.
  • Null-safe — x.equals(null) is false, never an exception.

And the rule that links the two methods:

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 6 sections

  • What breaks when you override only one
  • Writing them correctly
  • instanceof or getClass
  • Mutable keys break maps
  • What a good hash code looks like
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.