Lesson · Collections Framework
HashMap internals: buckets, chains and resize
14 min readHashMap Internals
A HashMap is an array of buckets plus one trick: turn a key into an index. Everything else (collisions, chains, resizing) is what happens when that trick meets reality.
Why HashMap matters
A HashMap turns a key into a bucket index with a few arithmetic steps, so a get() or put() usually finishes without scanning anything: expected O(1) on average, as long as hashes are well distributed. That single property is why it sits underneath caches, indexes, counters and half of every codebase you will ever read.
It is also the collection interviewers reach for first: get and put are O(1) on average, the worst case degrades with long chains, and both depend on two methods you write yourself: hashCode() and equals().
- Trace a put() and a get() from hashCode() to bucket to node.
- Explain the mask, and why the capacity is always a power of two.
- Say what a collision costs, and when equals() actually runs.
- Explain how a resize moves a chain: stay, or move by the old capacity.
- Describe when OpenJDK treeifies a bucket, and why mutable keys break lookups.
Implementation note: the bucket array, the index math, the spread function and the treeification thresholds in this lesson describe the commonly used OpenJDK implementation. The HashMap API promises the equals()/hashCode() contract and average O(1) behavior under a good hash; it does not guarantee any particular internal layout.
The bucket array
Internally a HashMap is an array of buckets. A key's bucket comes from a mask: index = spread & (n - 1), a bit-mask instead of a modulo. The mask only works because the capacity is a power of two, and every doubling adds exactly one mask bit (0011 → 0111 going from capacity 4 to 8): that one bit is what makes a resize cheap, and it is why an entry either stays at its index or moves by exactly the old capacity.
The default capacity is 16 with a load factor of 0.75, so the threshold is 12 entries: the 13th put triggers the first resize. Step through the visual below to watch a small table collide, fill up and resize.
HashMap · buckets 4 → 8
Table of 4
Start: 4 buckets, load factor 0.75 → resize threshold = 3 entries. (Real HashMaps start at 16; four keeps the picture readable.)
From key to bucket: the pipeline
Storing a key takes three steps. First the key's hashCode() runs. Then the hash is spread: hash ^ (hash >>> 16) folds the top half of the 32-bit value onto the bottom half, so hash codes that differ only in their high bits do not collapse onto one index. Finally the mask picks the bucket: index = spread & (capacity - 1).
Change the capacity below and watch the mask grow a bit at a time. Flip the hashing to a broken implementation that returns 1 for every key, and watch every index become 1: one bucket, one long chain, equals() at every node. That is the difference a good hashCode() buys.
Hash pipeline · hashCode → spread → index
real String.hashCode valuesbucket 0 holds 2 keys at capacity 16. Collisions are normal; chains absorb them, equals() separates them.
Collisions and chains
Two different keys can land in the same bucket: with four buckets, 10 & 3, 22 & 3 and 34 & 3 are all 2. HashMap accepts the collision: the bucket holds a chain of nodes, and a lookup walks it. The walk is cheaper than it sounds: for each node it compares the stored hash first and calls equals() only when the hashes match. A chain of distinct hashes is a row of int comparisons; two keys that genuinely share a hashCode pay an equals() at every visit, which is exactly why a lazy hashCode() is expensive.
In the OpenJDK implementation, a bucket that grows past eight entries can be converted into a red-black tree, and the worst case for that bucket drops from O(n) to O(log n). It is an optimization with conditions attached, not an API guarantee: the table must already hold at least 64 buckets (below that, doubling the table is the better fix, so the map grows instead of treeifying), a tree that later shrinks to six entries turns back into a chain, and none of these numbers are promised by the HashMap contract.
One more detail sits before the index math: the spread step from the pipeline above (hash ^ (hash >>> 16)) is what keeps high-bit differences from piling into one bucket.
Collision board · the chain walk, step by step
step through puts and getsFour buckets, threshold 3. The mask sends 10, 22 and 34 to the same bucket 2. Watch what each operation actually pays for.
The stepper above runs put, get and resize; this board is the collision walk itself.
Resize and rehash
One entry past the threshold and the table doubles: a new bucket array is allocated and every existing entry is placed again with index = spread & (newCapacity - 1). That is O(n) work inside a single put().
The move is cheaper than it looks: the mask grows by exactly one bit, so each entry has only two possible homes, its old index or oldIndex + oldCapacity. Resize splits every chain into a low half and a high half, reusing the cached hash. Because the table doubles, resizes happen exponentially rarely, so put stays O(1) amortized. The split is also why iteration order is unspecified: never rely on it.
What O(1) really means
Expected O(1) is a statement about averages under a good hash, not a stopwatch on every call. Each operation has a catch:
| Operation | Typical expectation | The catch |
|---|---|---|
| get() | expected O(1) | depends on hash distribution and the bucket's shape |
| put() | expected amortized O(1) | the put that triggers a resize is O(n) |
| remove() | expected O(1) | same walk as get() |
| bucket holding a chain | O(n) worst case | what a lazy hashCode() buys you |
| bucket converted to a tree | O(log n) | OpenJDK optimization, not an API guarantee |
A bad hashCode() never breaks correctness: the map still finds every key. It just pays equals() calls and node visits it should not have to.
What to remember
Two rules keep a HashMap fast, and one keeps it correct:
- equals() and hashCode() must agree, or equal keys are stored twice while lookups miss.
- Never mutate a key through a field that equals() or hashCode() reads: the entry stays in its original bucket, but the mutated key can never find it again.
- When you know the volume up front, pre-size: new HashMap<>((int) Math.ceil(expected / 0.75f)) reduces early resizes. Capacity rounds up to a power of two and the load factor still applies, so this is headroom, not a guarantee.
The mutable-key trap
Mutate a field that equals() or hashCode() reads and the key becomes a ghost. get() hashes the mutated state, lands in a different bucket and reports the key missing while the entry still sits in its original bucket. The map is not broken: the key moved on paper but not in the table. Keys should be immutable: String, Integer, enums, records.
Interview angles
What happens when two keys collide?+
They share a bucket and form a chain. The lookup walks the chain comparing stored hashes first and calling equals() only when the hashes match. In the OpenJDK implementation, a bucket whose chain passes eight entries can be treeified once the table holds at least 64 buckets, capping that bucket's worst case at O(log n) instead of O(n).
Why is capacity always a power of two?+
Index math is spread & (n - 1), a mask instead of a modulo. Doubling the table adds exactly one mask bit, so each entry either keeps its index or moves by the old capacity, and chains split into a low half and a high half. The spread step keeps hash codes that differ only in their high bits from sharing an index.
When does HashMap resize, and what does it cost?+
When size exceeds capacity × load factor (default 0.75). Every entry is rehashed into the new table: O(n) for that put, but rare enough that inserts stay O(1) amortized. Pre-size with new HashMap<>((int) Math.ceil(expected / 0.75f)) to reduce early resizes.
What is the difference between size, capacity and threshold?+
size is the number of entries stored. capacity is the length of the bucket array, always a power of two (default 16). threshold is capacity × load factor, the size at which the next put triggers a resize (default 12).
Why must equals() and hashCode() agree?+
A lookup finds the bucket by hash and the node by equals(). If two equal objects had different hashes they would land in different buckets and never meet. The rule is one-directional: equal objects must share a hashCode; different objects sharing one just means a collision.
Common misconception: hashCode() must be unique per object.
Why can a mutable key become unreachable?+
The entry's bucket was chosen from the key's hash at insert time. Mutating the key changes what get() computes, so it searches a different bucket while the entry still sits in the original one: present but unreachable. Use immutable keys: String, Integer, enums, records.