# How HashMap Works Internally

> Explain how HashMap works internally. What happens on put and get, how are collisions handled, what changed in Java 8, and when does resizing occur?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-hashmap-internals
Last updated: 2026-11-28

Difficulty: Advanced

## Question

Explain how HashMap works internally. What happens on put and get, how are collisions handled, what changed in Java 8, and when does resizing occur?

## Answer

If I could ask only one Java collections question in an interview, it would be this one, because it touches hashing, arrays, linked lists, trees, resizing and the equals-hashCode contract all at once. Let me walk you through it step by step.

A HashMap is essentially an array of buckets, called the table. Each slot holds a chain of entries (nodes). The default initial capacity is 16, always a power of two, and the default load factor is 0.75. The table is created lazily on the first put.

When you call put(key, value), the first step is computing the hash. HashMap calls key.hashCode() and then spreads it: h ^ (h >>> 16). XORing the high 16 bits into the low bits improves distribution, because the index uses only the low bits. The second step is finding the bucket index: (n - 1) & hash, where n is the table length. Since n is a power of two, this bitwise AND is equivalent to hash modulo n but faster. The third step: if the bucket is empty, place the new node there. If not, there is a collision. The map walks the chain, and for each node checks whether the hash is equal and the key is identical or equals. If a match is found, the old value is replaced. Otherwise the new node is appended to the tail of the chain. The get method follows the same path: hash, index, then compare with equals along the chain.

That is why the hashCode and equals contract is critical: hashCode picks the bucket, and equals confirms the exact key. Also, HashMap allows one null key, which is always stored at bucket 0 because its hash is defined as 0.

Java 8 introduced treeification. In older versions a long chain degraded lookup to O(n), which was also an attack vector, since an attacker could craft many keys with the same hash. In Java 8, when a bucket chain reaches 8 nodes (TREEIFY_THRESHOLD) and the table capacity is at least 64 (MIN_TREEIFY_CAPACITY), the chain is converted into a red-black tree, making worst-case lookup O(log n). If the table is smaller than 64, HashMap resizes instead of treeifying. When a tree shrinks to 6 nodes or fewer (UNTREEIFY_THRESHOLD), it converts back to a list. Tree ordering uses hash first, then compareTo if the keys are Comparable, then a tie-breaker.

Resizing: when the number of entries exceeds capacity times load factor (16 x 0.75 = 12), the table doubles and entries are redistributed. Thanks to power-of-two sizing, each node either stays at the same index or moves to index plus old capacity, decided by one extra hash bit, so no full rehash is needed. Resizing is O(n), so if you know the expected size, initialize with new HashMap<>(expected / 0.75 + 1) or use HashMap.newHashMap(n) in Java 19 and later.

The load factor is a time-versus-space trade-off. Lower values mean fewer collisions but more memory; higher values save memory but lengthen chains. 0.75 is a good default.

Other facts to know: average get and put are O(1); the iteration order is not guaranteed; HashMap is not thread-safe, and concurrent modification can corrupt it, in Java 7 even causing an infinite loop during resize; and mutable keys are dangerous because changing a key after insertion changes its hash.

## Code examples

### Collisions and bucket index

```
import java.util.*;

public class HashMapDemo {
    public static void main(String[] args) {
        String k1 = "Aa";
        String k2 = "BB";
        System.out.println(k1.hashCode() + " " + k2.hashCode());

        int h = k1.hashCode();
        int index = (h ^ (h >>> 16)) & (16 - 1);
        System.out.println("bucket " + index);

        Map<String, Integer> map = new HashMap<>();
        map.put(k1, 1);
        map.put(k2, 2);
        System.out.println(map.get(k1) + " " + map.get(k2) + " size=" + map.size());

        map.put(null, 99);
        System.out.println(map.get(null));
    }
}
```

Aa and BB are the classic colliding strings with the same hash 2112. They share a bucket but equals distinguishes them, so both are retrievable. The null key is allowed.

## Key points

- Table of buckets, default capacity 16, load factor 0.75, capacity is a power of two.
- Index = (n - 1) & (h ^ (h >>> 16)); collisions form a linked list.
- Java 8 treeifies a bucket at 8 nodes if capacity is at least 64, and untreeifies at 6.
- Resize doubles the table when size exceeds capacity times load factor.
- HashMap is not thread-safe and allows one null key.

## Common follow-up questions

- Why is the capacity always a power of two?
- What happens if hashCode returns a constant?
- How does resize avoid recomputing hashes?
- Why did Java 7 HashMap cause infinite loops in multithreaded code?

## Interview tips

- Walk through put step by step: hash, spread, index, compare, insert. A clear sequence beats a list of buzzwords.
- Quote the numbers: 16, 0.75, 8, 6 and 64. They signal that you have read the source.

## Concepts covered

HashMap, Hashing, Buckets, Treeification, Load Factor

Previous: [ArrayList vs LinkedList](https://www.internhack.in/learn/interview/java-interview/java-arraylist-vs-linkedlist) · Next: [HashMap vs Hashtable vs ConcurrentHashMap](https://www.internhack.in/learn/interview/java-interview/java-hashmap-hashtable-concurrenthashmap) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [How HashSet Works Internally](https://www.internhack.in/learn/interview/java-interview/java-hashset-internals)
- [Comparable vs Comparator and How TreeMap Sorts](https://www.internhack.in/learn/interview/java-interview/java-comparable-comparator-treemap)
- [Fail-Fast vs Fail-Safe Iterators](https://www.internhack.in/learn/interview/java-interview/java-fail-fast-vs-fail-safe)
- [Generics, Wildcards and Type Erasure](https://www.internhack.in/learn/interview/java-interview/java-generics-type-erasure)
- [JVM Memory: Heap, Stack, Metaspace](https://www.internhack.in/learn/interview/java-interview/java-jvm-memory-model)
- [Garbage Collection Basics and GC Roots](https://www.internhack.in/learn/interview/java-interview/java-garbage-collection-basics)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
