How HashMap Works Internally

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

Common follow-up questions

Interview tips

Concepts covered

HashMap, Hashing, Buckets, Treeification, Load Factor

More Core Java & Collections questions