Card 03/ 09

ConceptDifficulty: Intermediate1 min

What Happens When Two Keys Land in the Same Bucket

Two different keys, two different hash codes, and the same bucket. There are billions of possible hash codes and sixteen buckets to start with, so this is not an edge case — it is the normal state of a map.

A collision is not an error and nothing is overwritten. The bucket holds both entries, and a lookup searches the bucket with equals until it finds a matching key or runs out.

What a put does, depending on what is already in the bucket
The bucket holdsput doessize() changes
NothingStores the entryYes
An entry with a key that is not equalsStores this one alongside itYes
An entry with a key that is equalsReplaces that entry's valueNo

The third row is the only one that overwrites, and it is the behaviour people expect from a map: putting the same key twice keeps one entry with the second value. The first two rows are collisions, and both keys survive.

So a good hashCode is not one that never collides — that is impossible. It is one that spreads keys evenly, so that no bucket has many more than its share.