Explain how HashMap works internally.
basicCore Java › Java Collections Framework
HashMap keeps an array of buckets (Node<K,V>[] table). The key's hashCode() is spread, masked to an index, and the entry is stored in that bucket as a linked list (or a red-black tree when large). Lookup compares hash then equals.
- Index =
(n - 1) & hashwherenis a power of two. - Spread function:
h ^ (h >>> 16)mixes high bits into low bits. - Default capacity 16, load factor 0.75.
- Allows one
nullkey and manynullvalues; not thread-safe.
- Why is capacity always a power of two? So the index is a cheap bitmask instead of a modulo, and resize can split buckets without rehashing.
- Which is compared first,
equalsor hash? Stored hash first (cheap), then reference==, thenequals.