Interview notes

Everything about the hashCode()/equals() contract — grouped by topic so you can study one area at a time. Every answer is reproducible in the Playground.

The 5 golden rules

  • Override equals() and hashCode() together — always.
  • equal objects MUST have equal hash codes.
  • Unequal objects SHOULD (not must) have different hash codes.
  • Keys must be immutable in the fields hashCode/equals read.
  • hashCode() must be consistent — same object, same value, every call.

The contract, as a truth table

equals()hashCode()Valid?Consequence
truesameCorrect — the only valid combination for equal objects
truedifferentBROKEN — duplicates stored, get() returns null
falsesameLegal collision — resolved by equals(), just slower
falsedifferentIdeal — different keys, different buckets

The Contract2

Internals4

Pitfalls4

Resize & Treeify7

Collections2

Ready to prove it?

Every answer here is reproducible in the simulator.

Open Playground