Why this matters
- This is the single most consequential contract in the Java standard library:
HashMap,HashSet,Collectors.groupingByand 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.
Bucket index comes from the key's hash, not its insertion order — which is why HashMap iteration has no predictable sequence.
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()— anintderived 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, andfinalso 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
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)theny.equals(x). Broken most often by comparing across types. - Transitive — if
x.equals(y)andy.equals(z)thenx.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.