What is rehashing, when does it happen, and why does every entry have to be inserted again?
When the load factor passes a threshold, the table allocates a larger array (roughly double) and re-inserts all entries. Each entry must be re-hashed because its index h(k) = k mod N changes when N changes.
Rehashing keeps α small and therefore keeps operations fast:
putnotices that n / N would exceed the threshold (Java'sHashMap: 0.75; Python's dict: about 2/3).- A new array is allocated, typically about twice as large (often the next prime, for mod-based hashing).
- Every entry is inserted again with the new N.
Copying the cells in order would not work. Key 18 sits in cell 5 when N = 13, but with N = 29 it belongs in cell 18. Leaving it at 5 would make get(18) look in cell 18 and report it missing.
One rehash costs $O(n)$, but it happens only after the table has filled up by about as many entries as it already held. Spread over those inserts, each put still costs $O(1)$ amortized, the same argument as for a doubling ArrayList. The rehash happens automatically and is invisible in the API, but not in the timing: the one put that triggers it is very slow (see the real-time card).
Tip: if you know in advance that a map will hold a million entries, give it that capacity up front and skip all the intermediate rehashes. Java's constructor new HashMap<>(initialCapacity, loadFactor) sets both values.