Skip to content
UniCircle
HardConceptualCollections

How does HashMap work internally?

Question JAVA-COL-027

Explain how HashMap stores and finds entries. What happens on a collision, and what are the load factor and treeification?

Show the explanation

A HashMap keeps an array of buckets (default capacity 16). To place a key:

  1. Compute key.hashCode() and spread its bits (h ^ (h >>> 16)).
  2. Pick the bucket with index = hash & (capacity − 1) (capacity is a power of two).
  3. Walk that bucket: if a node has an equal key (hash equal and equals true), replace its value; otherwise add a new node.

Collisions (different keys, same bucket) are stored as a linked list in the bucket. Since Java 8, a bucket with more than 8 nodes is converted to a red-black tree (if the table has at least 64 buckets), so the worst case drops from O(n) to O(log n).

The load factor (default 0.75) controls resizing: when size > capacity × 0.75, the table doubles and entries are redistributed. Average get/put is O(1).

Java
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 10);
stock.merge("pen", 5, Integer::sum);    // 15
stock.getOrDefault("ink", 0);          // 0

Consequences worth stating: keys need a correct equals/hashCode; mutating a key after inserting it can make it unfindable; one null key is allowed; iteration order is not guaranteed (use LinkedHashMap for insertion order, TreeMap for sorted order); and HashMap is not thread-safe (use ConcurrentHashMap).

Original UniCircle question. Last reviewed 22 Oct 2026.