Java Zero to All All questionsPractise free
Interview questions › Core & Modern Java (8 -> 21) › Collections & Equals/HashCode Contracts

Walk through how HashMap stores and finds an entry, and why a bad hashCode degrades it to O(n).

Level II · JuniorCollections & Equals/HashCode Contracts
Short answer

HashMap computes the key's hashCode, spreads the bits to reduce clustering, and maps it to a bucket index; lookup then scans that bucket comparing keys with equals.

Explanation

If many keys collide into one bucket, that bucket becomes a long chain and operations degrade toward O(n) because you're doing linear search. Java 8 mitigates pathological collisions by converting a bucket to a balanced tree once it exceeds a threshold, giving O(log n) per bucket, but this only helps if keys are at least Comparable; the real fix is a well-distributed hashCode.

Common mistakes
  • Saying a bad hashCode only slows inserts.
  • Not mentioning Java 8 treeification limits the damage to O(log n).

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Collections & Equals/HashCode Contracts.

Practise free

More on Collections & Equals/HashCode Contracts