Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
How does `HashMap` work internally in Java 8+?
senior LeveljavaCore Language
In Simple Words:
HashMap is an array of buckets (Node<K,V>[]).
- Put: Computes
hash(key). Uses(n - 1) & hashto find bucket index. If empty, inserts node. - Collision: If bucket is occupied, checks
equals(). If not equal, appends to linked list. - Treeification (Java 8+): If a bucket's linked list length exceeds
TREEIFY_THRESHOLD(8) and array capacity is at least 64, the linked list converts to a Red-Black Tree (TreeNode<K,V>), reducing worst-case lookup fromO(n)toO(log n). - Resize: When size exceeds
capacity * loadFactor(default0.75), capacity doubles (e.g., 16 -> 32).