Skip to content
Codescope

Inside HashMap

An array of buckets, an index derived from the hash, and a chain when two keys land together.

core11 min8 steps

Before you start

A HashMap gives you "look up a value by any key" in constant time. How? The map converts the key into a number (the **hash**), uses that number to pick one of several **buckets**, and stores the entry there.

The magic is that going *back* to find the value works the same way: hash the key, pick the bucket, and there it is. No scanning through every entry.

This lesson opens up the buckets, shows a collision when two keys land in the same one, and explains why equals() and hashCode() must always agree or your map silently loses entries.

HashMap internal table

capacity 4 · one row per bucket
Rowfirst entrynext in chainsame bucket, different key
[0]null
[1]null
[2]null
[3]null

0 entries

Constant-time lookup means one index calculation, not a scan.

Step 1 of 8. A HashMap is an array. Underneath, a `HashMap` is an array of buckets — 16 by default, shown here as 4 to keep the picture readable. Every slot starts empty. The array is never searched from one end. The entire design exists to compute *which* slot to look in.

01 / 08

Step 01 / 08

A HashMap is an array

Underneath, a HashMap is an array of buckets — 16 by default, shown here as 4 to keep the picture readable. Every slot starts empty.

The array is never searched from one end. The entire design exists to compute *which* slot to look in.

hashmap-internals.javaJava
import java.util.HashMap;public class Main {    public static void main(String[] args) {        HashMap<Integer, String> byId = new HashMap<>();        byId.put(1, "Ana");     // Integer.hashCode() == the value        byId.put(2, "Ben");        byId.put(5, "Cal");     // 5 & 3 == 1 — collides with key 1        byId.get(5);            // find the bucket, then walk the chain        byId.put(1, "Ada");     // same key: replace, do not append    }}