Inside Java’s HashMap, from buckets to trees
HashMap promises constant-time get and put, and since Java 8 it stays fast even when many keys share a bucket. Here is the array, the chains, the resize that splits them, and the red-black trees that replace chains that grow too long.
01 What is behind put and get
You put a few names in a map and read one back. It feels instant whatever the size. To see why, and when it stops being true, you need the four parts inside: an array of buckets, chains of nodes, a resize rule and tree bins.
Everything here describes OpenJDK’s java.util.HashMap as it has worked since Java 8. The outputs and tree shapes come from real runs on JDK 17.
02 An array of buckets, a chain in each
A HashMap keeps one field that matters most: table, an array of Node. Each node holds the key’s hash, the key, the value and next, a pointer to the next node in the same bucket. The array’s length is always a power of two, 16 by default.
To pick a bucket, HashMap first mixes the key’s hashCode(): h ^ (h >>> 16) folds the top 16 bits into the bottom 16. Then hash & (length − 1) keeps the lowest bits, which is a cheap remainder for a power-of-two length. With 16 buckets only 4 bits pick the bucket, so without the mix, keys that differ only in their high bits would all collide.
| Key | hashCode() | h ^ (h >>> 16) | Bucket (& 15) |
|---|---|---|---|
| "ana" | 96724 | 96725 | 5 |
| "bo" | 3149 | 3149 | 13 |
| "mia" | 108101 | 108100 | 4 |
| "eve" | 100820 | 100821 | 5 |
String.hashCode() is defined by the Java spec, so these numbers are the same on every JVM and every run. "ana" and "eve" share bucket 5.
03 put and get, node by node
A put hashes the key, picks a bucket and walks its chain. If a node with the same hash and an equal key is there, the value is replaced. Otherwise a new node is linked on at the tail. Inside a bucket, nodes are compared by stored hash first; equals is only called when the hashes match.
- just stored
- checked, not it
- comparing now
- key matches
new HashMap<>() only records the defaults: capacity 16, load factor 0.75. The table field is still null; no buckets exist yet.
04 Resizing doubles the table and splits chains
The map tracks its size and a threshold, capacity × load factor. When a put makes size larger than the threshold, resize() doubles the array. With the defaults, that is the 13th entry in 16 buckets.
Because the length is a power of two, doubling adds exactly one bit to the bucket number. A node in bucket j either stays at j or moves to j + oldCapacity, depending on whether hash & oldCapacity is 0. resize() splits each chain into a “lo” list and a “hi” list in one pass. A tiny map makes it easy to watch.
- just placed
- waiting to move
- bucket picked
new HashMap<>(4) asks for 4 buckets; the first put allocates them. The threshold is 4 × 0.75 = 3, so a fourth entry will trigger a resize.
Reading the private table field by reflection after these four puts on JDK 17 shows exactly this: 8 buckets holding 1, 2, 5 and 6. A resize touches every node, so it costs time in proportion to the map’s size. Doubling keeps that cost rare enough that put stays constant time on average.
05 Long chains turn into red-black trees
If many keys land in one bucket, every lookup there walks a list. That happens with a poor hashCode, or on purpose: an attacker can send request parameters chosen to collide. Since Java 8, HashMap caps the damage with tree bins.
| Constant | Value | What it does |
|---|---|---|
| TREEIFY_THRESHOLD | 8 | A chain that grows past 8 nodes is turned into a tree |
| MIN_TREEIFY_CAPACITY | 64 | Below 64 buckets, resize the table instead |
| UNTREEIFY_THRESHOLD | 6 | A tree split down to 6 or fewer nodes on resize becomes a chain again |
The tree is a red-black tree of TreeNodes, a balanced binary search tree. It is ordered by hash first. Keys with equal hashes are ordered with compareTo when they are Comparable and of the same class, otherwise by a fixed tie-breaker. To build one, the example below uses nine 8-letter strings made of Aa and BB blocks. All nine have the hash code -540425984, and in a 64-bucket table they share bin 9. Sorted, AaAaAaAa is k1, AaAaAaBB is k2, and so on to BBAaAaAa, which is k9.
The tree shape and colours were read from a real HashMap on JDK 17. Red-black rules keep every path from the root to a leaf within a factor of two of the others, so the depth stays about log₂ n.
- compared, go on
- comparing now
- key matches
get("AaBBBBAa"), which is k7. Its hash leads to bin 9, which holds a tree. Nothing is compared yet.
equals calls.compareTo can order the keys.06 Watch a bin turn into a tree
This program puts colliding strings into a default map and reads the private table field after each of the 8th to 11th puts. Java blocks that reflection by default, so the command opens the package.
Real output on JDK 17. The 9th key makes the chain too long, but the table has only 16 buckets, so HashMap doubles it to 32 instead. Every key has the same hash, so they all stay in one bin. The 10th key doubles it again, to 64. Only the 11th, in a 64-bucket table, converts the bin into a tree.
07 When it bites
Tree bins are a safety net, not a fix. They need Comparable keys to work well; with colliding keys that cannot be compared, a lookup may have to search both sides of the tree. Fix a hashCode that collides rather than relying on them.
for (var e : map.entrySet())Iteration order is bucket orderA HashMap loops over its array, so the order follows the hashes and can change completely after a resize. Use LinkedHashMap when you need insertion order.new HashMap<>(100)The constructor takes buckets, not entriesThis gives 128 buckets and a threshold of 96, so the 97th put still resizes. Since Java 19, HashMap.newHashMap(100) sizes the table for 100 entries.map.put(k, v) // from two threadsNot safe across threadsTwo threads resizing or linking nodes at once can lose entries or leave the table inconsistent. Use ConcurrentHashMap, or guard every access with a lock.key.x = 5; // after putA key that changesThe node keeps the old hash and stays in the old bucket, so lookups for the changed key look somewhere else. Keys should be immutable.