The Plain Picture#
A post office sorting room with 16 pigeonholes. For each letter, a clerk applies a quick rule to the name — "add up the letters, keep the remainder after dividing by 16" — and drops the letter in that pigeonhole. To find Priya's letter, apply the same rule, go straight to one pigeonhole, and look through the few letters in it. You never search the other 15.
If one pigeonhole gets crowded, look-ups there slow down. When the whole room gets too full, the post office moves to a room with 32 pigeonholes and re-sorts everything.
The Real Names#
A
HashMap<K, V>stores key → value pairs. Look-up, insertion and removal by key are O(1) on average.Inside is an array of buckets (the pigeonholes), called the table. Its length (the capacity) is always a power of two — 16 by default.
The key's
hashCode()(Object-Oriented Programming Ch 8) is turned into a bucket index.Two different keys landing in the same bucket is a collision. Colliding entries are kept in a linked list in that bucket — and since Java 8, a crowded bucket is converted into a small balanced tree (treeification).
The load factor (default 0.75) decides when to grow: once the number of entries exceeds capacity × 0.75, the table doubles and every entry is re-placed (rehashing).
Under the Hood#
Step 1 — from key to bucket#
int h = key.hashCode(); // e.g. "Priya".hashCode() = 77382607
h = h ^ (h >>> 16); // "spread": mix the high bits into the low bits
int index = h & (capacity - 1); // keep only the low bits → 0 .. capacity-1Real values:
hash of "Priya" = 77382607, bucket (16) = 3, bucket (32) = 19Why a power of two? For a power of two, h & (capacity − 1) gives exactly the same result as h % capacity, but a bitwise AND is much
faster than division (Bit Manipulation (coming soon)). Because the AND keeps only the low bits, Java first XORs the high 16 bits into
the low 16 (h ^ (h >>> 16)), so keys whose hash codes differ only in their high bits don't all collide.
(A String's hashCode is computed from its characters, and cached inside the String after the first call — possible only because Strings are
immutable, Classes, Objects and Memory Ch 6.)
Step 2 — put and get#
table (capacity 16) index bucket ┌────┬──────────────────────────────────────────────┐ │ 0 │ null │ │ 1 │ null │ │ 2 │ [hash, "rahul"→22] → [hash, "aisha"→19] │ ← collision: a linked list in one bucket │ 3 │ [hash, "Priya"→200] │ │ .. │ │ │ 15 │ null │ └────┴──────────────────────────────────────────────┘ each entry (a Node) stores: hash, key, value, next
put(key, value):
Compute the hash and the bucket index.
Bucket empty → store a new node there. Done.
Otherwise walk the bucket's nodes: for each, compare the stored hash first (a cheap
intcomparison), and only if it matches, callequals. If an equal key is found → replace its value.Not found → add a new node to the bucket.
If the size now exceeds capacity × 0.75 → resize (Step 4).
get(key): same hash → same bucket → walk it comparing hash then equals → return the value, or null if not found.
This is exactly why the equals/hashCode contract matters (Object-Oriented Programming Ch 8): hashCode picks the bucket, and equals finds the key inside
it. If equal keys had different hash codes, get would search the wrong bucket.
Step 3 — collisions and treeification#
Collisions are unavoidable (there are infinitely many possible keys and only 2³² hash codes). They happen even for simple strings:
"Aa".hashCode()=2112 "BB".hashCode()=2112With a good hash function, entries spread evenly, each bucket holds about 0–2 entries, and operations are O(1) on average. But if many keys
land in one bucket — a poor hashCode, or an attacker deliberately sending colliding keys — that bucket's list grows long and look-ups become
O(n).
Java 8's fix: when one bucket's list reaches 8 entries (and the table has at least 64 buckets — otherwise it resizes instead), the list is turned into a red-black tree — a self-balancing binary search tree (trees: Binary Trees and Binary Search Trees (coming soon)). Look-ups in that bucket become O(log n) in the worst case. It turns back into a list if it shrinks to 6.
Step 4 — resizing#
When size > capacity × load factor (16 × 0.75 = 12 entries for a default map), the table doubles to 32, and every entry moves to its new bucket.
Because the capacity doubled, each entry either stays at the same index or moves to index + old capacity — decided by one extra bit of its hash
(that's why "Priya" moved from bucket 3 to 3 + 16 = 19 above). Resizing is O(n), but like ArrayList, doubling makes it amortized O(1) per put
(Big-O and Complexity Ch 7).
The load factor is a trade-off: lower (e.g. 0.5) → fewer collisions, more wasted memory; higher (e.g. 0.9) → less memory, more collisions.
0.75 is the default balance. If you know you'll store 1,000 entries, pre-size: new HashMap<>(2048) (or in Java 19+, HashMap.newHashMap(1000)),
avoiding repeated resizes.
Other facts interviewers ask#
One
nullkey is allowed (stored in bucket 0);nullvalues too. (HashtableandConcurrentHashMapallow neither.)No ordering guarantee — iteration order depends on bucket positions and can change after a resize (Ch 5 shows real output).
Not thread-safe — concurrent writes can corrupt it; use
ConcurrentHashMap(Concurrency).Mutable keys are dangerous — change a key's fields after inserting it, and its hash changes, so the map can't find it (Object-Oriented Programming Ch 8). Use immutable keys:
String,Integer, records.
The Map API — and the three patterns you'll write every week#
map.put(k, v);
map.get(k);
map.containsKey(k);
map.remove(k);
map.size();
map.getOrDefault(k, 0);
map.putIfAbsent(k, v);
map.keySet();
map.values();
map.entrySet();get returns null for a missing key — so int c = map.get(k) throws a NullPointerException when unboxing
(Classes, Objects and Memory Ch 8):
System.out.println(
missing.get("x") +
" " +
missing.getOrDefault("x", 0) +
" " +
missing.containsKey("x")
);
// null 0 falsePattern 1 — counting (frequency map):
String text = "the cell is the unit of life the end";
Map<String, Integer> count = new HashMap<>();
for (String w : text.split(" ")) count.put(w, count.getOrDefault(w, 0) + 1);
// same thing, shorter: count.merge(w, 1, Integer::sum);
// {cell=1, end=1, is=1, life=1, of=1, the=3, unit=1} (printed via a TreeMap for sorted order)Pattern 2 — grouping (map of lists):
Map<Integer, List<String>> byLength = new HashMap<>();
for (String w : text.split(" "))
byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w); // create the list the first time
// {2=[is, of], 3=[the, the, the, end], 4=[cell, unit, life]}This is how you build a graph's adjacency list (Graphs I (coming soon)) and group anagrams.
Pattern 3 — iterating entries:
for (Map.Entry<String, Integer> e : count.entrySet())
if (e.getValue() > 1) System.out.print(e.getKey() + "=" + e.getValue() + " ");
// the=3Iterate entrySet() — not keySet() followed by get(key) for each, which does a second look-up per key.
Check yourself
6 questionsWalk through what map.put("Priya", 200) does.
Show answerHide answer
Compute hashCode, spread it, AND with capacity−1 to get the bucket; if empty store a node; else walk the bucket comparing hash then equals,
replacing the value if the key exists or appending a node; then resize if size exceeds capacity × 0.75.
Why must a HashMap's capacity be a power of two, and why the h ^ (h >>> 16) step?
Show answerHide answer
So h & (capacity−1) can replace the slower %; the XOR mixes the high bits into the low bits that the AND keeps, reducing collisions.
What happens when many keys land in one bucket, in Java 8+?
Show answerHide answer
The bucket's list is converted into a red-black tree once it reaches 8 entries (if capacity ≥ 64), giving O(log n) worst case in that bucket.
When does a default HashMap resize, and what happens to each entry?
Show answerHide answer
When size exceeds capacity × 0.75 (12 for the default 16); the table doubles and each entry stays at its index or moves to index + old capacity.
Why is int c = map.get(k); dangerous, and what do you use instead?
Show answerHide answer
get returns null for missing keys, and unboxing null throws a NullPointerException; use getOrDefault(k, 0) or check containsKey.
What would happen if equals were overridden but hashCode weren't, for the key class?
Show answerHide answer
Equal keys would usually land in different buckets, so get and containsKey would fail to find them, and duplicates could be stored.