Inside Java's HashMap
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Modern Java HashMap contains sophisticated engineering optimizations. It combines linked lists, balanced red-black trees, and bitwise math to deliver robust performance.
Buckets and tree bins in modern Java
Since Java 8 a crowded bucket turns from a linked list into a red-black tree. Three constants inside java.util.HashMap decide when that happens.
// Constants inside java.util.HashMap (Java 8 and later)static final int TREEIFY_THRESHOLD = 8; // a chain of 8 becomes a red-black treestatic final int UNTREEIFY_THRESHOLD = 6; // a tree that shrinks to 6 becomes a list againstatic final int MIN_TREEIFY_CAPACITY = 64; // below 64 buckets, resize instead of treeifyingA tree bin is a HashMap bucket that has been converted from a linked list into a red-black tree. Early Java versions used simple linked lists for every bucket; in Java 8 and later, buckets convert to red-black trees when collisions become severe.
When a bucket reaches 8 elements and capacity is at least 64, it treeifies. Treeification guarantees worst-case O(log n) lookup time even under hash flooding attacks.
- Treeify threshold: bucket converts to red-black tree when chain length reaches 8.
- Minimum capacity: treeification only occurs if total table capacity is at least 64.
- Untreeify threshold: tree converts back to linked list when item count drops to 6.
- Worst-case safety: caps lookup latency at O(log n) rather than linear O(n).
- Insert key-value pair into bucket linked list.
- Check whether the bucket chain length has reached 8.
- Verify table capacity is at least 64; otherwise resize table first.
- Convert linked list nodes into balanced red-black tree nodes.
Bitwise hash spreading function
A HashMap picks a bucket with (capacity - 1) & hash after mixing the high bits into the low bits with h ^ (h >>> 16). The example shows two keys that only spreading can separate.
Example 1 · Observing Bitwise Hash Spreading in Action
public class HashSpreadDemo { public static int spread(int h) { return h ^ (h >>> 16); }
public static void main(String[] args) { int cap = 16; int mask = cap - 1; // 15, binary 1111
// Two keys differing only in high 16 bits int h1 = 0x00010003; int h2 = 0x00020003;
int rawIdx1 = h1 & mask; int rawIdx2 = h2 & mask; System.out.println("Without spread: " + rawIdx1 + ", " + rawIdx2);
int spreadIdx1 = spread(h1) & mask; int spreadIdx2 = spread(h2) & mask; System.out.println("With spread: " + spreadIdx1 + ", " + spreadIdx2); }}Without spread: 3, 3 With spread: 2, 1
What this code does
- Without spreading, both hash codes mask to the exact same bucket 3.
- Spreading folds upper bits into lower bits, avoiding collision.
- The two keys resolve to distinct buckets 2 and 1.
Java HashMap capacity is always a power of two. Indexing uses bitwise AND instead of modulo: (capacity - 1) & hash. Without spreading, only the lowest bits of the hash code affect the bucket index. Java applies a bitwise shift: (h = key.hashCode()) ^ (h >>> 16).
This folds high 16 bits into low 16 bits, distributing bucket placements. Consider table capacity 16 with mask 15 (0000 1111 in binary). Suppose a key has hash code 0x12345678. Without spreading, hash & 15 only inspects the lowest 4 bits 1000 (index 8).
The top 28 bits have zero influence on bucket selection. Spreading XORs the top 16 bits into the bottom 16 bits. The lowest bits become 1100, producing bucket index 12. Now all 32 bits influence bucket selection evenly.
- Fast index mask:
(capacity - 1) & hashreplaces slower modulo division. - Bit spreading formula:
(h ^ (h >>> 16))blends upper bits into lower bits. - Collision reduction: prevents collisions when keys differ only in upper bit positions.
Predict the output
Predict the bucket
Read each snippet and pick what it prints.
Round 1 of 2
Undefined iteration order and mental model
A HashMap visits its buckets in index order, so keys do not come out in the order you added them. Use LinkedHashMap when you need insertion order.
Example 2 · HashMap visits buckets by index, not by insertion order
import java.util.HashMap;import java.util.Map;
public class BucketOrderDemo { public static void main(String[] args) { Map<Integer, String> byId = new HashMap<>(); byId.put(100, "first"); byId.put(5, "second"); byId.put(33, "third"); System.out.println(byId); }}{33=third, 100=first, 5=second}What this code does
- The keys 100, 5 and 33 are put in buckets 4, 5 and 1 of a 16-bucket table (key & 15).
- Printing walks the buckets from 1 up, so 33 comes first even though it was added last.
- The exact order is an implementation detail, so never depend on it.
Example 3 · LinkedHashMap keeps insertion order
import java.util.LinkedHashMap;import java.util.Map;
public class MapOrderDemo { public static void main(String[] args) { Map<String, Integer> linked = new LinkedHashMap<>(); linked.put("payments", 1); linked.put("orders", 2); linked.put("refunds", 3);
System.out.print("Linked: "); for (String k : linked.keySet()) { System.out.print(k + " "); } System.out.println(); }}Linked: payments orders refunds
What this code does
- A
LinkedHashMapalso links its entries in the order they were added. - The keys print as payments, orders, refunds, exactly as put.
- It costs a little extra memory per entry for the links.
HashMap iteration visits array buckets from index 0 to capacity - 1. Within each bucket, it traverses nodes in chain order. Because rehashing shifts entries between buckets, iteration order can change after resizing. Never write code that relies on HashMap iteration order; use LinkedHashMap for predictable ordering. Note that this explanation is a simplified model of the OpenJDK implementation.
- Undefined order: iteration sequence reflects bucket indices and collision chains.
- Order instability: inserting new keys can trigger rehashing and alter iteration order.
- Predictable alternative: use
LinkedHashMapto maintain insertion order.
Next step
Check your understanding
10 quick questions