HashMap internals

Mid-level Always asked 7 min

On this page

The question

How does HashMap work internally?

30-second answer

A HashMap is an array of buckets. put() calls the key's hashCode(), spreads it with h ^ (h >>> 16) and masks it with capacity minus one to pick a bucket. If a key in that bucket is equal by equals(), the value is replaced; otherwise a node is added. When the size passes capacity times load factor, the table doubles.

Understand it

Keys, buckets and the resize

Explore

6 entries stay within the threshold of 12 (16 × 0.75), so the table keeps its 16 buckets.

6
View as text

Rows of 16 small boxes are the buckets of a HashMap table; a table of 32 or 64 buckets takes two or four rows. Each key put into the map is a small bar under the bucket its hash picks, and keys that share a bucket stack into a chain. Badges above show the capacity, the threshold and the number of entries. Below, a mark says whether the table resized and a badge lists every table size it went through. Controls set the number of entries, from 1 to 24, the initial capacity, 4 or 16, and the load factor, 0.5, 0.75 or 1.0.

12 entries stay within the threshold of 12 (16 × 0.75), so the table keeps its 16 buckets. Two buckets hold a chain of 2 keys each.

Inserting 13 entries crossed the threshold once, so the table doubled from 16 to 32 buckets; the threshold is now 24. Each key stayed put or moved 16 buckets on. A second row of 16 buckets appears, and keys move straight down into it.

Inserting 7 entries crossed the threshold twice, so the table doubled from 4 to 16 buckets; the threshold is now 12. The badge reads 4, 8, 16.

Inserting 9 entries crossed the threshold once, so the table doubled from 16 to 32 buckets; the threshold is now 16. Each key stayed put or moved 16 buckets on. A lower load factor resizes earlier and leaves more buckets empty.

Rows of 16 small boxes are the buckets of a HashMap table; a table of 32 or 64 buckets takes two or four rows. Each key put into the map is a small bar under the bucket its hash picks, and keys that share a bucket stack into a chain. Badges above show the capacity, the threshold and the number of entries. Below, a mark says whether the table resized and a badge lists every table size it went through. Controls set the number of entries, from 1 to 24, the initial capacity, 4 or 16, and the load factor, 0.5, 0.75 or 1.0.

12 entries stay within the threshold of 12 (16 × 0.75), so the table keeps its 16 buckets. Two buckets hold a chain of 2 keys each.

Inserting 13 entries crossed the threshold once, so the table doubled from 16 to 32 buckets; the threshold is now 24. Each key stayed put or moved 16 buckets on. A second row of 16 buckets appears, and keys move straight down into it.

Inserting 7 entries crossed the threshold twice, so the table doubled from 4 to 16 buckets; the threshold is now 12. The badge reads 4, 8, 16.

Inserting 9 entries crossed the threshold once, so the table doubled from 16 to 32 buckets; the threshold is now 16. Each key stayed put or moved 16 buckets on. A lower load factor resizes earlier and leaves more buckets empty.

Takeaway: The table is a power of two. An insert that takes the entries above capacity times load factor doubles it, and each key stays or moves by the old capacity.

When a bucket's chain becomes a tree

Step by step

Two keys whose hashes collide land in bin 5 of a 64-bucket table, so the bin holds a linked list of 2 nodes.

Step 1 of 5
View as text

A box labelled bin 5 stands for one bucket of a HashMap table; a badge gives the table size. Numbered circles are the nodes of the keys that collide in that bucket.

Two keys whose hashes collide land in bin 5 of a 64-bucket table, so the bin holds a linked list of 2 nodes.

More colliding keys join the end of the list. A lookup walks it node by node, calling equals(), so 8 nodes can cost 8 checks. A dashed arrow runs along the 8 nodes.

A ninth node passes the limit of 8, and the table has at least 64 buckets, so the bin is treeified. A smaller table would resize instead. Marks say the chain passed 8 nodes and the table has 64 or more buckets.

The bin becomes a red-black tree ordered by hash, so a lookup takes O(log n) steps instead of walking every node. The 9 nodes move into a tree four levels deep.

A resize leaving 6 or fewer nodes turns it back into a list. The thresholds 8, 64 and 6 are OpenJDK's HashMap implementation, not part of the Map contract. The table doubles to 128 buckets and the tree splits into a list of 5 nodes in bin 5 and a list of 4 in bin 69.

A box labelled bin 5 stands for one bucket of a HashMap table; a badge gives the table size. Numbered circles are the nodes of the keys that collide in that bucket.

Two keys whose hashes collide land in bin 5 of a 64-bucket table, so the bin holds a linked list of 2 nodes.

More colliding keys join the end of the list. A lookup walks it node by node, calling equals(), so 8 nodes can cost 8 checks. A dashed arrow runs along the 8 nodes.

A ninth node passes the limit of 8, and the table has at least 64 buckets, so the bin is treeified. A smaller table would resize instead. Marks say the chain passed 8 nodes and the table has 64 or more buckets.

The bin becomes a red-black tree ordered by hash, so a lookup takes O(log n) steps instead of walking every node. The 9 nodes move into a tree four levels deep.

A resize leaving 6 or fewer nodes turns it back into a list. The thresholds 8, 64 and 6 are OpenJDK's HashMap implementation, not part of the Map contract. The table doubles to 128 buckets and the tree splits into a list of 5 nodes in bin 5 and a list of 4 in bin 69.

Takeaway: Colliding keys form a list in their bucket. Past 8 nodes on a table of at least 64 buckets, OpenJDK turns the list into a red-black tree.

What put doesput hashes the key and masks the hash to a bucket. If an equal key is already in the bucket, its value is replaced. Otherwise a new node is added, and if the size is now above the threshold the table doubles.equal keynew keysize above thresholdput(key, value)hashCode, high bitsmixed inbucket: hash & (n-1)Replace valueAdd a nodeDouble the table
What put doesput hashes the key and masks the hash to a bucket. If an equal key is already in the bucket, its value is replaced. Otherwise a new node is added, and if the size is now above the threshold the table doubles.equal keynew keysize above thresholdput(key, value)hashCode, high bitsmixed inbucket: hash & (n-1)Replace valueAdd a nodeDouble the table
What put() does: hash, bucket, replace or add, resize

In code

String key = "ana";
int h = key.hashCode();          // 96724
int spread = h ^ (h >>> 16);     // 96725: high bits mixed into low bits
int bucket = spread & (16 - 1);  // 5, the same as spread % 16
Which of 16 buckets the key ana lands in
Map<String, Integer> visits = new ConcurrentHashMap<>();
visits.put("ana", 0);
// run by two threads, 100,000 times each:
 Wrong visits.put("ana", visits.get("ana") + 1);   // read, then write: typically loses updates
 Right visits.merge("ana", 1, Integer::sum);       // one atomic update: always 200,000
Counting visits from two threads
Two threads write to different binsThread 1 merges the key ana, which locks only bin 5. Thread 2 merges the key ben, which locks only bin 10. Neither waits for the other, so both updates run at the same time.Thread 1:merge(ana)Locks bin 5 onlyThread 2:merge(ben)Locks bin 10 onlyNo waiting: both runat once
Two threads write to different binsThread 1 merges the key ana, which locks only bin 5. Thread 2 merges the key ben, which locks only bin 10. Neither waits for the other, so both updates run at the same time.Thread 1:merge(ana)Locks bin 5 onlyThread 2:merge(ben)Locks bin 10 onlyNo waiting: both runat once
Two threads write to different bins of a ConcurrentHashMap
Map<String, Integer> plain = new HashMap<>();
plain.put(null, 1);                          // stored in bucket 0
Map<String, Integer> shared = new ConcurrentHashMap<>();
 Wrong shared.put(null, 1);                         // NullPointerException
HashMap accepts one null key; ConcurrentHashMap rejects null

Solve it

How many times does a default HashMap resize while filling 1,000 entries?

A job loads 1,000 products into new HashMap<>() on every request, and a profiler shows time in resize(). Count the resizes, explain their cost and remove them.

  1. Start from the defaults. Capacity 16 and load factor 0.75 give a threshold of 12. The map doubles when its size passes the threshold.
  2. Walk the doublings. Entry 13 makes it 32, then entries 25, 49, 97, 193, 385 and 769 double it again: 7 resizes, ending at 2,048 buckets.
  3. Price each resize. A resize allocates a new table and moves every entry, so the last one alone moves 768 entries.
  4. Size it up front. HashMap.newHashMap(1000) (Java 19) picks a capacity whose threshold is at least 1,000: zero resizes. new HashMap<>(1000) is a trap: capacity 1,024, threshold 768, one resize.
  5. Check. Same map, same contents, no resize() in the profile.
 Wrong Map<String, Product> grows = new HashMap<>();          // 7 resizes for 1,000 entries
 Wrong Map<String, Product> almost = new HashMap<>(1000);     // threshold 768: still 1 resize
 Right Map<String, Product> sized = HashMap.newHashMap(1000); // threshold 1,536: none
for (Product p : products) sized.put(p.sku(), p);
Ask for the number of entries, not the capacity
A default HashMap doubling while 1,000 entries go inThe map starts with 16 buckets. Entry 13 doubles it to 32, entry 25 to 64, entry 49 to 128, entry 97 to 256, entry 193 to 512, entry 385 to 1,024 and entry 769 to 2,048, where the 1,000 entries fit.The rest of the 1,000 entriesBuckets, and the entry that doubles them#13#25#49#193#385#769#971632641282565121,0242,048
A default HashMap doubling while 1,000 entries go inThe map starts with 16 buckets. Entry 13 doubles it to 32, entry 25 to 64, entry 49 to 128, entry 97 to 256, entry 193 to 512, entry 385 to 1,024 and entry 769 to 2,048, where the 1,000 entries fit.The rest of the 1,000 entriesBuckets, and the entry that doubles them#13#25#49#193#385#769#971632641282565121,0242,048
A default HashMap doubling while 1,000 entries go in

How to answer

  • Bucket index: (h ^ (h >>> 16)) & (capacity - 1), so the capacity is always a power of two.
  • A lookup compares stored hashes first, then calls equals() on the keys in that one bucket.
  • Colliding keys share a bucket as a linked list, or as a red-black tree once the list grows long.
  • The default capacity is 16 and the default load factor 0.75, so the first resize comes with the 13th entry.
  • put() returns the previous value for the key, or null when there was none.

Common mistakes

  • Saying a HashMap stores entries in insertion order or sorted order; its iteration order follows the buckets.
  • Saying hashCode() alone finds the entry; equal hashes still need equals() to confirm the key.

Follow-up questions

What happens when two keys collide in a HashMap?

Both keys land in the same bucket and are stored as a chain of nodes. A lookup goes to that bucket and walks the chain, comparing hashes and then calling equals() until it finds the key. Many collisions turn O(1) lookups into a walk through a long chain, which is why a good hashCode() spreads keys evenly.

  • A collision means the same bucket index, not necessarily the same hashCode().
  • New nodes are added at the end of the bucket's list.
  • A poor hashCode(), such as a constant, puts every key in one bucket.

See it in the infographic: Keys, buckets and the resize See it in the infographic: When a bucket's chain becomes a tree

What are the load factor and the resize of a HashMap?

The load factor is how full the table may get before it grows. The threshold is capacity times load factor: with 16 buckets and 0.75 it is 12, so the 13th entry doubles the table to 32 buckets. A resize allocates the new array and moves every node, which costs O(n), so presize a map whose size you know.

  • Default: capacity 16, load factor 0.75, threshold 12.
  • A resize doubles the capacity; each key stays at index i or moves to i plus the old capacity.
  • A lower load factor means fewer collisions but more memory; a higher one the opposite.
  • The table is allocated on the first put, not in the constructor.
new HashMap<>(4, 0.75f);   // 7 puts: 4 -> 8 -> 16 buckets
new HashMap<>(16, 0.5f);   // 9 puts: 16 -> 32 buckets

See it in the infographic: Keys, buckets and the resize

What is treeification in a HashMap?

Since Java 8, a bucket whose list passes 8 nodes becomes a red-black tree, so a lookup in a crowded bucket takes O(log n) instead of O(n). It only happens when the table has at least 64 buckets; a smaller table is resized instead. When a resize leaves 6 or fewer nodes in a tree bin, it turns back into a list.

  • OpenJDK constants: TREEIFY_THRESHOLD 8, MIN_TREEIFY_CAPACITY 64, UNTREEIFY_THRESHOLD 6.
  • These are implementation details of OpenJDK, not part of the Map contract.
  • It protects against many colliding keys, for example from a poor hashCode() or crafted input.
  • Comparable keys keep the tree lookup at O(log n) even when their hashes are equal.

See it in the infographic: When a bucket's chain becomes a tree

What is the difference between HashMap and ConcurrentHashMap?

HashMap is not thread-safe: concurrent puts can lose updates or corrupt the table. ConcurrentHashMap is safe for concurrent use without locking the whole map: in OpenJDK reads take no lock, and a write locks only its one bin, or uses a compare-and-set on an empty bin. It also offers atomic compound operations like merge() and computeIfAbsent(), and rejects null keys and values.

  • Threads writing to different bins of a ConcurrentHashMap do not block each other.
  • Use merge() or compute(), not get() then put(), for an atomic read-modify-write.
  • Its iterators are weakly consistent and never throw ConcurrentModificationException.
  • Collections.synchronizedMap() locks the whole map for every call instead.
Map<String, Integer> visits = new ConcurrentHashMap<>();
visits.merge("ana", 1, Integer::sum);  // atomic per key

See it in the infographic: Keys, buckets and the resize

Can a HashMap have null keys or null values?

Yes. A HashMap allows one null key, stored in bucket 0 because its hash is 0, and any number of null values. Because get() returns null both for a missing key and for a null value, use containsKey() to tell them apart. ConcurrentHashMap and Hashtable allow neither and throw NullPointerException.

  • One null key; putting it again replaces its value.
  • get() returning null is ambiguous: missing key or null value.
  • ConcurrentHashMap forbids null so that a null from get() always means "absent".
Map<String, Integer> m = new HashMap<>();
m.put(null, 1);
m.put(null, 2);                            // size 1, get(null) is 2
new ConcurrentHashMap<String, Integer>()
    .put(null, 1);                         // NullPointerException

See it in the infographic: Keys, buckets and the resize

Why is the capacity always a power of two?

Because then hash & (capacity - 1) keeps the low bits of the hash and gives the same result as a modulo, only faster. It also makes a resize cheap: each key either stays at its index or moves by exactly the old capacity, decided by one bit of its hash.

Why does HashMap compute h ^ (h >>> 16)?

The mask only keeps the low bits, so hashes that differ only in their high bits would all collide in a small table. XOR-ing the upper 16 bits into the lower 16 lets the high bits influence the bucket, at the cost of one shift and one XOR.

Is the iteration order of a HashMap stable?

No guarantee. Iteration follows the bucket array, so the order depends on the hashes and the capacity, and a resize can change it between two loops over the same keys. Use LinkedHashMap for insertion order or TreeMap for sorted order.

Check yourself

1. A new HashMap<>() with the default capacity and load factor already holds 12 entries. What happens when you put a 13th distinct key?
Show answers
  • The table doubles to 32 buckets: Correct. 13 is above the threshold of 16 times 0.75, which is 12, so the table doubles.
  • Nothing; 13 entries fit in 16 buckets: Incorrect. The map resizes on the threshold, not when every bucket is full.
  • The table grows to 17 buckets: Incorrect. The capacity stays a power of two, so it always doubles.
2. In a table of 64 buckets, keys keep colliding in one bucket. When does OpenJDK turn that bucket into a red-black tree?
Show answers
  • When a ninth node joins a list of 8: Correct. The list is treeified once it passes TREEIFY_THRESHOLD, 8 nodes, on a table of at least 64 buckets.
  • As soon as two keys collide: Incorrect. Short lists are cheaper than trees, so a bucket stays a list until it passes 8 nodes.
  • Never; HashMap buckets are always lists: Incorrect. Since Java 8, a long chain on a large enough table becomes a tree.
3. A default HashMap of 16 buckets gets 9 keys with the same hashCode(). What does the bucket hold afterwards?
Show answers
  • Still a list; the table resized to 32 buckets: Correct. Below 64 buckets OpenJDK resizes instead of treeifying, and equal hashes stay together in one list.
  • A red-black tree: Incorrect. Treeification needs a table of at least 64 buckets.
  • The keys spread over 9 buckets: Incorrect. Keys with the same hash always share a bucket, whatever the capacity.