You use HashMap a hundred times a day. But can you explain — in detail — what happens on a single map.put?
In this episode we crack open java.util.HashMap and trace every operation:
→ The internal structure — an array of Node buckets
→ How put(key, value) computes the index with (n − 1) & hash
→ Why bit-AND is faster than hash % n (and how Java enables the trick)
→ Collisions and chaining — when two keys land in the same bucket
→ How get() walks the chain and matches via equals()
→ How remove() unlinks a Node from the linked list
→ Resizing — the moment HashMap doubles capacity and rehashes everything
→ Treeify — the Java 8 optimization that drops worst-case from O(n) to O(log n)
→ Three production traps that bite engineers: mutable keys, the hashCode/equals contract, and thread-safety
⏱ Chapters
00:06 The question most engineers can't answer
00:24 What HashMap actually is
00:38 The library-shelves analogy
00:58 Internal structure — array of buckets
01:15 The Node — hash, key, value, next
01:32 put() in 4 steps
01:57 Worked example — six inserts at capacity 16
02:21 Collisions = chaining
02:39 Why (n − 1) & hash, not hash % n
03:02 get() — the 4-move lookup
03:20 Trace: looking up "C"
03:39 remove() — unlinking from the chain
03:53 Resize trigger (loadFactor 0.75)
04:13 Capacity 4 → 8 rehash trace
04:36 The amortized O(1) story
04:54 The complexity headline
05:14 Java 8 treeify — chain to red-black tree
05:37 Three production traps
06:05 Three interview questions you can now answer
06:26 Recap
06:47 What should we crack open next?
📚 Playlist: Java Internals — Cracking Open the JDK
🔗 codebrainery.com — the tech blog
Subscribe @codebrainery for more Java internals — line by line, no hand-waving.
#Java #HashMap #JVM #DataStructures #SoftwareEngineering #Codebrainery