HashMap Internals: Buckets, Hashing, and Resizing
Fast recall
Quick revision
Core answer
Whether you understand hashing, collision resolution, and the Java 8 treeification upgrade — not just the API surface
Saying 'it's just a key-value store backed by an array' without explaining how hashCode maps to a bucket or how collisions are resolved
Mention the Java 8 upgrade from linked-list chains to red-black trees at TREEIFY_THRESHOLD=8, explain load factor math, and describe the pre-sizing pattern for production maps
Interview-ready guide
Interview answer
HashMap is a bucket array where each slot is indexed by the key's hash — put("name", "John") XOR-mixes upper and lower 16 bits of hashCode(), then masks with capacity - 1 to pick a bucket. That's why put and get are O(1) on average.
Collision handling:
- Two keys in the same bucket form a linked list — worst case O(n) before Java 8
- Java 8 treeification: chains exceeding 8 nodes convert to a Red-Black tree, capping worst case at O(log n)
- Reverts to a list below 6 nodes to avoid overhead on short chains
Resizing:
- Default capacity 16, load factor 0.75 → resize triggers at just 12 entries
- Doubles the array and rehashes everything — O(n), runs synchronously on the triggering thread
- Can cause p99 latency spikes in hot paths; fix:
new HashMap<>(2048)for ~1000 entries
equals/hashCode contract:
- Override
equals()but forgethashCode():putstores in one bucket,getlooks in another — silently returns null - Java records auto-generate both correctly — use them for map keys
I recommend pre-sizing HashMap in hot paths and using records or carefully implemented equals()/hashCode() for keys.
HashMap Internals: Buckets, Hashing, and Resizing
Direct Answer
A HashMap stores key-value pairs in a Node array (the bucket table). Each key's hashCode is mixed with a spread function to pick a bucket index. Collisions form linked-list chains that treeify into red-black trees once a bucket exceeds 8 entries (Java 8+). When the map exceeds 75% capacity it doubles the array and rehashes every entry.
Common Mistakes & Pitfalls
Saying 'it's just a key-value store backed by an array' without explaining how hashCode maps to a bucket or how collisions are resolved
Check your understanding
Answer these without looking back at the article.
- What happens if two objects have the same hashCode but are not equal?
- How does ConcurrentHashMap differ from Collections.synchronizedMap()?
- Why must HashMap keys be immutable?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.