Card 02/ 09

ExampleDifficulty: Intermediate1 min

HashMap Example: A Hundred Keys Across Sixteen Buckets

Why a map does not stay small, and what it becomes when every key hashes alike.

How evenly keys spread across buckets decides how much work each lookup does. A new HashMap has sixteen buckets; counting word occurrences puts a hundred distinct words into it:

java
Map<String, Integer> counts = new HashMap<>();
for (String word : words) {
    counts.merge(word, 1, Integer::sum);
}
What a well-spread hundred keys look like across buckets
BucketsKeysKeys per bucket, on averageA lookup compares
16100About 6About 6 keys
256100Under 10 or 1 key
256100 with identical hashesAll 100 in oneUp to 100 keys

The first row is why a map does not stay at sixteen buckets: six comparisons per lookup is six times the cost of one, so the map grows its bucket array and spreads the keys out again.

The third row matters most and rarely happens by accident. It is a map whose keys' hashCode returns the same number for everything: every lookup becomes a walk, and the map has quietly become a list.