The full picture
🎬 HashMap internals: buckets, chains, trees, resize
1 / 5A HashMap is an array of buckets (default capacity 16, here 8 for clarity). put("cat", 9) → hash("cat") is spread (h ^ h>>>16) and masked: index = hash & (n-1) → bucket 3.
- Hash spreading:
(h = key.hashCode()) ^ (h >>> 16)mixes high bits into low bits because the index mask only uses low bits — defends against bad hashCode distributions. - Treeify threshold 8, untreeify 6: chosen because with a decent hash, chain length follows a Poisson distribution — 8 collisions is ~1 in 10 million, so trees are a pathological-case defense (including hash-flooding DoS), not the normal path.
- Resize is expensive: every entry rehashed/moved; pre-size with
new HashMap<>(expected / 0.75f + 1)(orHashMap.newHashMap(expected)in 19+) for large known loads. - Iteration order: none guaranteed — use
LinkedHashMapfor insertion/access order (and as an LRU viaremoveEldestEntry),TreeMapfor sorted keys.