Card 03/ 09
All 9 cards
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.
| The bucket holds | put does | size() changes |
|---|---|---|
| Nothing | Stores the entry | Yes |
An entry with a key that is not equals | Stores this one alongside it | Yes |
An entry with a key that is equals | Replaces that entry's value | No |
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.