← Back to Week 3 Hub

HashMap Hashing & Buckets

Keys get hashed into bucket slots. That's why a HashMap can find any value instantly — and why the order looks random.

The big idea: a HashMap stores key/value pairs. When you put("TX", "Austin"), Java runs the key through a hash function to decide which of 16 buckets to store the value in. When you later call get("TX"), it hashes the same key and jumps directly to that bucket.

Hash & Put demo

Key
"TX"
hash()
bucket index (16)
Preset pairs (states & capitals from the workbook):

Internal buckets (capacity 16)

Current HashMap state (as println would show it)
{}
Why the output order looks random: HashMap prints entries in bucket order, not insertion order. Look at the bucket grid above — that's exactly the order you'll see from System.out.println(map). Adding the same 5 states in a different order produces the same bucket layout, because each key always hashes to the same slot.

Tip: try adding CT → Hartford, CA → Sacramento, TX → Austin from the presets and watch which buckets light up. Then try them in reverse order — same buckets.

← ArrayList Operations HashMap Operations & Iteration →