- Home
- Interview Questions
- Java
- How does HashMap work internally, including collisions, resi…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: HashMap stores entries in an array of buckets, using the key's hash to choose a bucket. Colliding keys are chained in a linked list that turns into a red-black tree once a bucket holds more than 8 entries and the table has at least 64 buckets. The table doubles in size when the entry count exceeds capacity times load factor.
Detailed explanation
1. Structure
Internally, HashMap holds an array called table of Node<K,V> objects. Each node stores the key, the value, the cached hash and a reference to the next node in the same bucket. The table is created lazily on the first put. Its default capacity is 16 and its default load factor is 0.75. The capacity is always a power of two.
2. Computing the bucket index
- HashMap first calls
key.hashCode(). It then spreads the bits withh ^ (h >>> 16), which mixes the high bits into the low bits. - The index is
(n - 1) & hash, where n is the table length. Because n is a power of two, this gives the same result as a modulo operation but is faster. - Without the bit spreading, keys whose hashes differ only in the high bits would all land in the same bucket.
- A null key is allowed. Its hash is treated as 0, so it always goes to bucket 0.
3. put() and collisions
If the bucket is empty, a new node is placed there. If it is not empty, HashMap walks the bucket and compares each node's hash and then its key, using == or equals(). If it finds a matching key, it replaces the value and returns the old value. Otherwise it appends a new node to the end of the list. Java 8 changed this from head insertion to tail insertion.
4. Treeification (Java 8+)
- When a bucket's list grows beyond
TREEIFY_THRESHOLD(8), the bucket is converted to a red-black tree ofTreeNodeobjects. Lookup in that bucket then improves from O(n) to O(log n). - Treeification only happens if the table capacity is at least
MIN_TREEIFY_CAPACITY(64). If the table is smaller, HashMap resizes instead, because spreading entries across more buckets is cheaper. - When a tree bucket shrinks to
UNTREEIFY_THRESHOLD(6) or fewer nodes during a resize split, it converts back to a list. The gap between 8 and 6 prevents the bucket from switching back and forth. - Inside a tree, nodes are ordered by hash. When hashes tie, HashMap uses
compareToif the keys are mutually Comparable, and otherwise falls back to a tie-breaking rule.
5. Resizing
When size exceeds threshold (capacity multiplied by load factor, so 12 for the defaults), the table doubles in size. Because capacity is a power of two, each entry either stays at the same index or moves to index + oldCapacity. The bit hash & oldCap decides which. Each bucket therefore splits into a low list and a high list, and no hash needs to be recomputed.
6. get()
get() computes the index the same way, checks the first node, and then walks the list or searches the tree. The average cost is O(1). The worst case is O(log n) for a treeified bucket and O(n) before Java 8.
Example
class BadKey {
final int id;
BadKey(int id) { this.id = id; }
@Override public int hashCode() { return 42; } // every key collides
@Override public boolean equals(Object o) {
return o instanceof BadKey && ((BadKey) o).id == id;
}
}
Map<BadKey, String> map = new HashMap<>();
for (int i = 0; i < 1000; i++) {
map.put(new BadKey(i), "v" + i);
}
// All 1000 entries share one bucket. Once the table has grown
// to at least 64 buckets, that bucket is treeified. BadKey is not
// Comparable, so tree ordering falls back to tie-breaking and
// lookups may still degrade toward a linear search.
// The fix is a well-distributed hashCode().
System.out.println(map.get(new BadKey(500))); // v500Common mistakes
- Saying a bucket treeifies as soon as it holds more than 8 entries. Candidates often forget the minimum table capacity of 64.
- Believing the index is
hashCode() % capacity. HashMap actually spreads the bits and then uses a bitwise AND withn - 1. - Mutating a key's fields after insertion. The stored hash no longer matches, so
get()looks in the wrong bucket and the entry becomes effectively unreachable. - Calling HashMap thread-safe or thinking it is fine for concurrent writes. Concurrent puts can lose updates or corrupt the structure. Use
ConcurrentHashMapinstead.
Follow-up questions
- Why must the HashMap capacity be a power of two?
- How does ConcurrentHashMap in Java 8 achieve thread safety without locking the whole map?
- If you know you will store 1000 entries, what initial capacity should you pass and why?
Interview tip: Walk through the sequence in order: hash spreading, index calculation, collision chaining, treeification at 8 with a minimum capacity of 64, and resize at 0.75 load. Quoting these exact thresholds immediately marks you as experienced.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More hard Java questions
- How is a lambda different from an anonymous inner class in Java beyond shorter syntax? · 1 ans
- How do you implement a generic interface and its functions in Java? · 1 ans
- How does the JVM manage memory for Java applications? · 1 ans
- How do abstract classes differ from interfaces in Java? · 1 ans
- How do final variables differ from static final variables? · 1 ans
Related Questions
- How is a lambda different from an anonymous inner class in Java beyond shorter syntax? · Java · 1 ans
- What makes an interface a functional interface, and what does @FunctionalInterface actually do? · Java · 1 ans
- What is the difference between HashSet, LinkedHashSet and TreeSet, and when would you use each? · Java · 1 ans
- How do you implement a generic interface and its functions in Java? · Java · 1 ans
- What are the constraints in Java generics and why are they used? · Java · 1 ans
- How do abstract classes differ from interfaces in Java? · Java · 1 ans
- What are the advantages of using interfaces in Java? · Java · 1 ans
- How do final variables differ from static final variables? · Java · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)