Hashing and HashMap

Lesson 13 of 20

Follow a key through hashCode into its bucket, watch chains grow on collisions, and see a rehash in action.

The big picture

Meet the hash map

A hash map turns a key into a number, a number into a bucket, and a bucket into O(1) lookups — on average. Collisions and load factor are the two things that keep it honest.

The hash idea

key.hashCode() gives a spread-out 32-bit int; the map folds it into a bucket with (n - 1) & hash. Same key, same bucket, every time.

Buckets & chains

Two keys can land in one bucket — a collision. Java chains them in a list inside the bucket and compares with equals().

Cost math

One hash plus one short chain is O(1) on average. If every key collides into one bucket, lookups degrade to O(n).

Load factor 0.75

When size passes capacity × 0.75, HashMap resizes to double the buckets and re-hashes every key.

Map vs Set

HashMap stores key → value pairs; HashSet is the same machinery with only keys. Both rely on hashCode and equals.