Quick revision
The short answer
When many keys land in one bucket, a Java 8+ HashMap first keeps them in a singly linked list, so a lookup in that bucket costs O(n). Once the bucket reaches TREEIFY_THRESHOLD (8) nodes and the table has at least MIN_TREEIFY_CAPACITY (64) slots, the bucket is converted into a red-black tree of TreeNodes, ordered by hash, then by compareTo for Comparable keys of the same class, then by a tie-break, which brings the worst case down to O(log n). If the table is smaller than 64, HashMap resizes instead, and a tree bin turns back into a list when a resize split leaves it with 6 or fewer nodes.
What to remember
In this answer, we saw that colliding keys in a Java 8+ HashMap first form a singly linked list in their bin, with O(n) lookups. When a bin reaches 8 nodes and the table has at least 64 slots, it becomes a red-black tree of TreeNodes, ordered by hash, then by compareTo for Comparable keys of the same class, then by a tie-break; with a smaller table, HashMap resizes instead. A tree bin turns back into a list when a resize split leaves it with 6 or fewer nodes, and the worst-case lookup in a crowded bin improves from O(n) to O(log n).
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
When many keys land in one bucket, a Java 8+ HashMap first keeps them in a singly linked list, so a lookup in that bucket costs O(n). Once the bucket reaches TREEIFY_THRESHOLD (8) nodes and the table has at least MIN_TREEIFY_CAPACITY (64) slots, the bucket is converted into a red-black tree of TreeNodes, ordered by hash, then by compareTo for Comparable keys of the same class, then by a tie-break, which brings the worst case down to O(log n). If the table is smaller than 64, HashMap resizes instead, and a tree bin turns back into a list when a resize split leaves it with 6 or fewer nodes.
Why this question is asked
Collisions are normal in any hash table, and most of the time they cost almost nothing. They become a problem when a poor hashCode() or a deliberate attack piles many keys into one bucket, and then a map that should answer in nanoseconds starts scanning long chains. Java 8 added a defence for this, and interviewers ask about it to see whether we understand what happens inside the map rather than just that lookups are O(1). In this answer, we will recap buckets and collisions, follow a bucket as it grows from a list into a tree, see how the tree orders its keys, look at when it shrinks back, and finish with the lookup cost in each state.
1A Quick Recap of Buckets and Collisions
A HashMap stores its entries in an array called the table, and each slot is a bucket, which the source code calls a bin. The bucket for a key is chosen from the key's hash with (n - 1) & hash, where n is the table length. A collision means two different keys land in the same bucket, either because their hashes are equal or because their low bits match.
Each entry is a Node object holding the hash, the key, the value and a next reference. When several nodes share a bucket, the next references link them into a chain, a singly linked list, and a lookup walks that chain comparing the stored hash and then calling equals().
2Stage 1: A Linked List in the Bin
With a well-spread hash and the default load factor of 0.75, almost every bucket holds zero, one or two nodes, so walking the chain is trivial. The trouble starts when many keys share a bucket. We can force that with keys whose hashCode() is constant.
Notice that the stored-hash shortcut does not help here, because every node has hash 42. Each step of the walk calls equals(). With n keys in the bucket, a lookup is O(n), and a miss always walks the whole chain.
3Stage 2: Turning the Bin Into a Tree
As put() appends a node to a chain, it counts how long the chain is. When the chain reaches the threshold TREEIFY_THRESHOLD, which is 8 (the check runs while appending, so the conversion happens as the ninth node goes in), put() calls treeifyBin().
treeifyBin() first checks the size of the whole table. If the table has fewer than MIN_TREEIFY_CAPACITY slots, 64, it does not build a tree at all. It resizes the table instead. The reasoning is that in a small table a long chain is more likely to come from crowding than from equal hashes, and doubling the table will spread the keys out for less cost than a tree. Only when the table already has 64 or more slots does it replace the Node objects in that bucket with TreeNode objects and balance them into a red-black tree, a self-balancing binary search tree that keeps its height within about twice the logarithm of its size.
- Append the node to the bin's chain
- Chain at TREEIFY_THRESHOLD (8)?YesCall treeifyBin()NoDone, still a list
- Table length at least 64?
MIN_TREEIFY_CAPACITYYesConvert bin to a red-black treeNoResize the table instead - Lookups in this bin now O(log n)
4 steps in order. Play them, or step through them one at a time.
4How the Tree Orders Keys
A binary search tree needs a way to decide whether a key goes left or right. HashMap cannot simply call compareTo, because keys are not required to be Comparable. So it uses a sequence of rules.
First it compares the hashes. Keys with different hashes, which is common in a bin since only the low bits had to match, are ordered by hash value alone. If the hashes are equal, it checks whether the key's class is Comparable to itself, for example String, Integer or a record that implements Comparable<Order>, and whether both keys are of the same class; if so, it uses compareTo. If that is not possible or compareTo returns 0, it uses a tie-break order, comparing class names and then System.identityHashCode, just so that insertion can put the node somewhere consistent.
The tie-break is only good for insertion. A lookup cannot use the identity hash of a key it has not seen, so when hashes are equal and the keys are not comparable, find() may have to search both subtrees. This is why Comparable keys benefit most from tree bins.
| Bin state | Typical cause | Lookup in the bin |
|---|---|---|
| empty or 1 node | well-spread hashes | O(1) |
| list, up to 8 nodes | ordinary collisions | O(k), k small |
| list, longer, table < 64 | small table: resize comes first | O(k) until the resize |
| tree, distinct hashes or Comparable keys | weak hashCode or attack | O(log k) |
| tree, equal hashes, not Comparable | constant hashCode on a plain class | can approach O(k) |
5When a Tree Bin Turns Back Into a List
Trees cost memory and are only worth it for crowded bins, so HashMap converts them back. During a resize, each bin is split into the nodes that stay at index i and the nodes that move to i + oldCap. If either half has UNTREEIFY_THRESHOLD, 6, or fewer nodes, that half is turned back into a plain list of Nodes. Removing entries can also untreeify a bin, using a quick check of the tree's shape rather than an exact count.
The gap between 8 for treeifying and 6 for untreeifying is deliberate. It stops a bin that hovers around one size from flipping between list and tree on every few operations, a pattern called hysteresis.
6The Lookup Cost in Each State
Putting it together: a lookup first computes the hash and finds the bucket in O(1). Inside the bucket, it is O(1) for an empty or single-node bin, O(k) for a list of k nodes, and O(log k) for a tree bin. Before Java 8, the worst case for a bucket holding every key was O(n). Since Java 8, with keys that have distinct hashes or are Comparable, it is O(log n). That does not make a bad hashCode() acceptable, since O(log n) is still far slower than O(1), but it stops one bad bucket from turning a map into a linear scan.
7Follow-up questions
Why is the threshold 8 and not, say, 2?
Because with a reasonable hash function long bins are extremely rare, and trees are expensive. The HashMap source explains that at a load factor of 0.75, bin sizes follow roughly a Poisson distribution with a mean of about 0.5, which makes a bin of 8 nodes less likely than one in ten million. So trees appear almost only when hashes are bad or keys are hostile. With a threshold of 2, ordinary collisions would create trees all the time, doubling the memory of those nodes and adding balancing work, while a two-node list is already faster to scan than a tree.
What does a TreeNode cost in memory compared with a plain Node?
A Node holds the hash, key, value and next fields, about 32 bytes on a 64-bit JVM with compressed references. TreeNode extends LinkedHashMap.Entry, which adds before and after links, and then adds parent, left, right and prev references and a red flag, which brings it to roughly 56 bytes, close to double. The source itself says TreeNodes are about twice the size of regular nodes, which is another reason they are used only for crowded bins.
Does ConcurrentHashMap treeify too?
Yes. It uses the same thresholds of 8, 6 and 64, and wraps the tree in a TreeBin object that also carries a small lock so readers can keep going while a writer rebalances.
8Conclusion
In this answer, we saw that colliding keys in a Java 8+ HashMap first form a singly linked list in their bin, with O(n) lookups. When a bin reaches 8 nodes and the table has at least 64 slots, it becomes a red-black tree of TreeNodes, ordered by hash, then by compareTo for Comparable keys of the same class, then by a tie-break; with a smaller table, HashMap resizes instead. A tree bin turns back into a list when a resize split leaves it with 6 or fewer nodes, and the worst-case lookup in a crowded bin improves from O(n) to O(log n).
Open with
In a Java 8 or later HashMap, keys that land in the same bucket are first kept as a singly linked list of Node objects in that bin, so a lookup in that bin is linear: it compares the stored hash and then calls equals on each node.
Then, if they want more
When put appends to a chain that has reached TREEIFY_THRESHOLD, which is 8, it calls treeifyBin. If the table has fewer than MIN_TREEIFY_CAPACITY slots, 64, it resizes the table instead, because spreading the keys is cheaper than a tree in a small map. Otherwise it converts the bin into a red-black tree of TreeNodes.
The tree orders nodes by hash first, then by compareTo if the keys are Comparable and of the same class, and finally by a tie-break on class name and identity hash code, which is only good for insertion; for equal hashes on non-comparable keys, a lookup may need to search both subtrees.
A tree bin turns back into a list when a resize split leaves 6 or fewer nodes, and the gap between 6 and 8 avoids flip-flopping. So the worst-case lookup in a crowded bin goes from O(n) to O(log n).
The threshold is 8 because, with a good hash and load factor 0.75, a bin that long is rarer than one in ten million, and TreeNodes are roughly twice the size of Nodes.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What happens inside a Java 8+ HashMap when many keys end up in the same bucket, and what...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/feaef9c3b7/