"How does HashMap work internally?" is probably the most asked Java interview question. Most candidates say "it uses hashing and buckets" and stop there. The interviewer then asks a follow-up, and that is where the round is won or lost.
Here are the 7 follow-ups I see most often, with answers you can say out loud.
1. What actually happens when you call put()?
HashMap keeps an array of buckets (a Node<K,V>[] table ). On put(key, value) :
It calls key.hashCode() and spreads the bits: hash = h ^ (h >>> 16) . This mixes the high bits into the low bits so small tables still get a good spread.
It finds the bucket with index = (n - 1) & hash , where n is the table size (always a power of two).
If the bucket is empty, the new node goes there. If not, it walks the bucket and uses equals() to check whether the key already exists. If it does, the value is replaced. If not, the node is added at the end.
One-line answer: hashCode() picks the bucket, equals() picks the entry.
2.…