Video in progress
What happens step by step inside HashMap when map.put(key, value) is called?
The key's hashCode() is taken and its high bits are mixed into the low ones, then the bucket index is found with (n - 1) & hash. If the bucket is empty, a new node is placed there; otherwise equals is used to look for a matching key, and either the value is replaced or the node is appended to the end of the chain.
📖 Answer
A simplified sequence (Java 8+):
hash = key.hashCode() ^ (key.hashCode() >>> 16): the upper 16 bits are "spread" down. The reason: the index is taken from the low bits only, so in a small table the high bits would never be used at all.- If the table hasn't been created yet, it is created on the first
putwith length 16 (lazily). index = (table.length - 1) & hash. Since the length is always a power of 2, this is the same as%, but faster.- If the bucket is empty, a new
Nodeis placed. - If the bucket is occupied, the hashes are compared first, and if they match,
==orequals. If the key is found, the value is replaced and the old value is returned. - If it isn't found, the node is appended to the end of the chain. When the chain grows past 8 nodes and the table is at least 64 long, the bucket turns into a tree.
- If
++size > threshold, a resize happens and the table doubles.
Map<String, Integer> m = new HashMap<>();
Integer old = m.put("a", 1); // null
old = m.put("a", 2); // 1, the old value
That is why a bad hashCode (for example, always 42) crams all entries into a single bucket and the HashMap effectively turns into a list.
Sign up to mark studied questions and save your progress.