How HashMap Works Inside
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)"How does HashMap work internally?" is the most asked Java collections question. The interviewer is checking whether you can explain put and get step by step, and whether you know what goes wrong with collisions, resizing and changing keys.
put and get: hashCode, spreading and the bucket index
A HashMap is a Map that stores key-value pairs in an array of buckets. The key's hashCode picks the bucket and equals finds the exact key inside it, so lookups take O(1) time on average.
Walk through put and get in three steps. The program computes the bucket of four names in a 16-bucket table.
Example 1 · From hashCode to bucket index
public class BucketIndexDemo { static int spread(int h) { return h ^ (h >>> 16); }
public static void main(String[] args) { String[] names = {"Asha", "Ravi", "Kiran", "Meena"}; int buckets = 16;
for (String name : names) { int h = name.hashCode(); int hash = spread(h); int index = (buckets - 1) & hash; System.out.println(name + ": hashCode " + h + " -> bucket " + index); } }}Asha: hashCode 2050251 -> bucket 4 Ravi: hashCode 2539842 -> bucket 4 Kiran: hashCode 72504801 -> bucket 3 Meena: hashCode 74220576 -> bucket 12
What this code does
String.hashCodeis fixed by the Java specification, so these numbers are the same on every computer.(16 - 1) & hashkeeps only the lowest 4 bits, giving a bucket from 0 to 15. Asha and Ravi both land in bucket 4: a collision, even with only four keys.
put(key, value) runs three steps. It calls key.hashCode(), mixes the high bits into the low bits with h ^ (h >>> 16) (called spreading), and finds the bucket with (n - 1) & hash, where n is the number of buckets. Then it walks that bucket: if a node has the same hash and an equals key, it replaces the value; otherwise it adds a new node.
get(key) repeats the same hash and index steps, then walks only that one bucket, comparing hash first and equals second. That is why get is O(1) on average: it never looks at the other buckets. The Maps module in Section 4 and the Hash Tables from Scratch module in Section 6 cover this in depth. Revise: How a HashMap works (opens in a new tab).
Order of execution
What put(key, value) does
Put the steps of one put in the order HashMap runs them.
(n - 1) & hash gives the same bucket as hash % n for positive hashes, but it is faster and never negative.Collisions: chains and Java 8 treeification
A collision is when two different keys land in the same bucket. HashMap keeps all of them in a small chain, and equals tells them apart, so nothing is lost.
Two different keys can land in the same bucket. The program shows that Aa and BB share a hash code, yet both entries survive.
Example 2 · Collisions do not lose data
import java.util.HashMap;import java.util.Map;
class RollKey { final int roll;
RollKey(int roll) { this.roll = roll; }
@Override public int hashCode() { return 42; // terrible on purpose: every key collides }
@Override public boolean equals(Object o) { return o instanceof RollKey other && other.roll == roll; }}
public class CollisionDemo { public static void main(String[] args) { System.out.println("\"Aa\" -> " + "Aa".hashCode() + ", \"BB\" -> " + "BB".hashCode());
Map<String, Integer> codes = new HashMap<>(); codes.put("Aa", 1); codes.put("BB", 2); System.out.println("Aa=" + codes.get("Aa") + ", BB=" + codes.get("BB") + ", size " + codes.size());
Map<RollKey, String> students = new HashMap<>(); for (int roll = 1; roll <= 1000; roll++) { students.put(new RollKey(roll), "Student " + roll); } System.out.println(students.get(new RollKey(777)) + ", size " + students.size()); }}"Aa" -> 2112, "BB" -> 2112 Aa=1, BB=2, size 2 Student 777, size 1000
What this code does
- "Aa" and "BB" have the same hash code, so they share a bucket, and
equalskeeps them apart. - With a constant
hashCode, all 1000 keys sit in one bucket. The answers stay correct; only speed suffers, which Java 8's tree bins limit to O(log n).
Collisions slow get down but never lose data.
In Java 8 and later, when one bucket grows past 8 nodes (TREEIFY_THRESHOLD) and the table has at least 64 buckets, the chain turns into a red-black tree, a self-balancing sorted tree. The worst-case lookup then drops from O(n) to O(log n). If the table is smaller than 64, HashMap resizes instead, and a tree shrinks back to a list at 6 nodes.
Load factor 0.75, capacity and resizing
The load factor is how full a HashMap may get before it grows. The default is 0.75: once the size passes the threshold, capacity × 0.75 (12 for 16 buckets), the table doubles and every entry is rehashed.
Resizing depends on capacity times load factor. The program adds 100 entries and prints each moment the table doubles.
Example 3 · When does a HashMap resize?
public class ResizeDemo { public static void main(String[] args) { int capacity = 16; int threshold = (int) (capacity * 0.75f); int size = 0;
for (int entry = 1; entry <= 100; entry++) { size++; if (size > threshold) { int old = capacity; capacity = capacity * 2; threshold = (int) (capacity * 0.75f); System.out.println("Entry " + entry + ": resize " + old + " -> " + capacity + ", new threshold " + threshold); } } System.out.println("100 entries end in " + capacity + " buckets");
int requested = 100; int rounded = 1; while (rounded < requested) { rounded = rounded * 2; } System.out.println("new HashMap<>(100) starts with " + rounded + " buckets, threshold " + (int) (rounded * 0.75f)); }}Entry 13: resize 16 -> 32, new threshold 24 Entry 25: resize 32 -> 64, new threshold 48 Entry 49: resize 64 -> 128, new threshold 96 Entry 97: resize 128 -> 256, new threshold 192 100 entries end in 256 buckets new HashMap<>(100) starts with 128 buckets, threshold 96
What this code does
- This is a simplified model of HashMap's sizing rules: the 13th entry pushes the size past 12, so the 16 buckets double to 32.
- Passing 100 as the capacity gives 128 buckets with threshold 96, so the 97th entry still triggers a resize.
Capacity is the number of buckets (16 by default, created on the first put).
A resize is O(n), but it is rare, so put stays O(1) on average. new HashMap<>(100) rounds the capacity up to the next power of two, 128, whose threshold is 96, so it still resizes once while filling 100 entries. Java 19 added HashMap.newHashMap(100), which sizes the map for 100 entries with no resize.
Predict the output
How many resizes?
Each loop fills a new HashMap with default settings. Pick the number of resizes.
Round 1 of 3
Fill with 12 entries. How many resizes?
null keys, and why keys should be immutable
Keys must not change after put. The program changes a key's field and shows that get can no longer find the entry.
Example 4 · A mutable key loses its entry
import java.util.HashMap;import java.util.Map;import java.util.Objects;
class Student { int roll; // not final: this is the bug final String name;
Student(int roll, String name) { this.roll = roll; this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Student s && s.roll == roll && s.name.equals(name); }
@Override public int hashCode() { return Objects.hash(roll, name); }}
public class MutableKeyDemo { public static void main(String[] args) { Map<Student, Integer> marks = new HashMap<>(); Student ravi = new Student(7, "Ravi"); marks.put(ravi, 88); System.out.println("Before change: " + marks.get(ravi));
ravi.roll = 70; // key changed after put System.out.println("After change: " + marks.get(ravi)); System.out.println("Old key: " + marks.get(new Student(7, "Ravi"))); System.out.println("Size: " + marks.size());
Map<String, Integer> fines = new HashMap<>(); fines.put(null, 10); fines.put(null, 20); fines.put("Library", null); System.out.println("null key -> " + fines.get(null) + ", size " + fines.size()); }}Before change: 88 After change: null Old key: null Size: 1 null key -> 20, size 2
What this code does
- After
rollchanges, the new hash points to another bucket, and a lookup with the old values failsequals. The entry is stuck: size is still 1. - The second
put(null, ...)replaces the first, because there is only one null key. A null value is fine.
HashMap allows one null key (its hash is taken as 0, so it lives in bucket 0) and any number of null values. Hashtable and ConcurrentHashMap allow neither.
A key must not change after you put it in the map. The entry was stored under the old hash, so after a change get looks in the wrong bucket, or finds the node but fails equals. The entry is still inside, taking memory, but you can no longer reach it. That is why String, Integer and records make good keys: they are immutable and have correct equals and hashCode. Revise: equals and hashCode in collections (opens in a new tab).
Find the bug
Find the key bug
Each snippet breaks HashMap lookups. Tap the wrong line, then check the fix.
Two Seats with the same row must be the same key.
Round 1 of 3The two-minute model answer, plus follow-ups
Say the answer in this order, and draw the buckets on paper while you talk. The program is the same answer as a small working hash map.
- HashMap is an array of buckets; each bucket holds nodes with hash, key, value and next.
putcomputeshashCode, spreads it, finds the bucket with(n - 1) & hash, then updates a matching key or adds a node.getfinds the same bucket and compares hash, thenequals: O(1) on average.- Collisions form a chain; since Java 8 a chain longer than 8 becomes a red-black tree, so the worst case is O(log n).
- Default capacity 16, load factor 0.75: past the threshold the table doubles and entries are rehashed.
- One null key is allowed; keys should be immutable with a correct
equals/hashCodepair; it is not thread-safe, so useConcurrentHashMapacross threads.
Example 5 · Your own small hash map
import java.util.Objects;
class MiniHashMap<K, V> { static class Node<K, V> { final int hash; final K key; V value; Node<K, V> next;
Node(int hash, K key, V value, Node<K, V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } }
private Node<K, V>[] table = newTable(4); private int size;
@SuppressWarnings("unchecked") private static <K, V> Node<K, V>[] newTable(int n) { return (Node<K, V>[]) new Node[n]; }
static int hash(Object key) { if (key == null) return 0; int h = key.hashCode(); return h ^ (h >>> 16); }
V put(K key, V value) { int hash = hash(key); int index = (table.length - 1) & hash; for (Node<K, V> n = table[index]; n != null; n = n.next) { if (n.hash == hash && Objects.equals(n.key, key)) { V old = n.value; n.value = value; return old; } } table[index] = new Node<>(hash, key, value, table[index]); if (++size > table.length * 3 / 4) { resize(); } return null; }
V get(Object key) { int hash = hash(key); for (Node<K, V> n = table[(table.length - 1) & hash]; n != null; n = n.next) { if (n.hash == hash && Objects.equals(n.key, key)) { return n.value; } } return null; }
private void resize() { Node<K, V>[] old = table; table = newTable(old.length * 2); for (Node<K, V> head : old) { Node<K, V> n = head; while (n != null) { Node<K, V> next = n.next; int index = (table.length - 1) & n.hash; n.next = table[index]; table[index] = n; n = next; } } System.out.println("resized to " + table.length + " buckets"); }
int size() { return size; }
int buckets() { return table.length; }}
public class MiniHashMapDemo { public static void main(String[] args) { MiniHashMap<String, Integer> fees = new MiniHashMap<>(); fees.put("Tuition", 85000); fees.put("Hostel", 60000); fees.put("Exam", 30000); fees.put("Library", 2000); fees.put("Lab", 5000); fees.put("Tuition", 90000); // same key: value replaced
System.out.println("Tuition: " + fees.get("Tuition")); System.out.println("Bus: " + fees.get("Bus")); System.out.println("size " + fees.size() + ", buckets " + fees.buckets()); }}resized to 8 buckets Tuition: 90000 Bus: null size 5, buckets 8
What this code does
putandgetfollow the model answer: spread the hash, mask it to a bucket, then compare hash andequalsalong the chain.- It starts with 4 buckets (threshold 3), so the 4th new key triggers one resize to 8. The repeated
Tuitiononly replaces the value. - Real HashMap also adds tree bins and keeps chain order on resize; this version keeps only the core idea.
Next step
Check your understanding
12 quick questions