Skip to content

Inside Java’s HashMap, from buckets to trees

Deep diveUnder the hood

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.

Java
Map<String, Integer> ages = new HashMap<>();
ages.put("ana", 31);
ages.put("bo", 25);
ages.put("mia", 29);
ages.put("eve", 22);
ages.get("eve"); // 22

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.

Four String keys in a table of 16 buckets (real values)
KeyhashCode()h ^ (h >>> 16)Bucket (& 15)
"ana"96724967255
"bo"3149314913
"mia"1081011081004
"eve"1008201008215

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.

Four puts, then a get
Step 1 of 9
Bucket —Size 0
table · 16 bucketsnull: no table yet
  • 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.

— key

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.

new HashMap<>(4): the fourth put doubles the table
Step 1 of 8
Threshold 3Buckets 4
table · 4 buckets, then 8
0empty
1empty
2empty
3empty
  • 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.

0 size

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.

The constants in HashMap that control tree bins
ConstantValueWhat it does
TREEIFY_THRESHOLD8A chain that grows past 8 nodes is turned into a tree
MIN_TREEIFY_CAPACITY64Below 64 buckets, resize the table instead
UNTREEIFY_THRESHOLD6A 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 same nine keys as a chain and as the tree bin HashMap builds from it
bin 9 as a chain · up to 9 compares
k1
k2
k3
k4
k5
k6
k7
k8
k9
null
bin 9 · red-black tree
k4black
k2red
k1black
k3black
k6red
k5black
k8black
k7red
k9red

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.

get(k7) in the tree bin
Step 1 of 5
bin 9 · red-black tree
k4black
k2red
k1black
k3black
k6red
k5black
k8black
k7red
k9red
What find() did
Empty
  • 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.

0 compares
Chain of n nodesUp to n comparesEach lookup walks the list. A thousand colliding keys mean up to a thousand equals calls.
Tree bin of n nodesAbout log₂ nEach level halves what is left, as long as 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.

Bins.java
import java.lang.reflect.Field;
import java.util.HashMap;
public class Bins {
public static void main(String[] args) throws Exception {
// "Aa" and "BB" have the same hashCode, so every mix of them does too.
String[] p = {"Aa", "BB"};
HashMap<String, Integer> map = new HashMap<>();
Field tableField = HashMap.class.getDeclaredField("table");
tableField.setAccessible(true);
int n = 0;
for (String a : p) for (String b : p) for (String c : p) for (String d : p) {
String key = a + b + c + d;
map.put(key, ++n);
if (n < 8 || n > 11) continue;
Shell
$ javac Bins.java
$ java --add-opens java.base/java.util=ALL-UNNAMED Bins
8 keys: 16 buckets, bin 9 is a Node
9 keys: 32 buckets, bin 9 is a Node
10 keys: 64 buckets, bin 9 is a Node
11 keys: 64 buckets, bin 9 is a TreeNode

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.

08 Check yourself

Question

A map with 16 buckets has 8 keys in one bin, all with the same hash. You put a 9th such key. What does HashMap do?

Question

The table grows from 8 to 16 buckets. Where can a node from bucket 3 end up?

Question

Why does HashMap compute h ^ (h >>> 16) before picking a bucket?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?