Skip to lesson

How HashMap works inside

A HashMap is an array of buckets. It uses the key's hashCode() to jump straight to one bucket, and equals() to find the right key inside that bucket. That is why get stays fast even with lakhs of entries.

An array of buckets

A bucket is one slot of the array inside a HashMap. A key's hash code decides its bucket, and one bucket can hold several entries, kept together in a chain.

Inside a HashMap is an array, and each slot of it is a bucket. The map turns a key into a bucket number and jumps straight to that slot. Below, four students' marks show each key's hash code and bucket.

Inside a HashMap with 16 buckets: Meera goes to bucket 0, Riya to bucket 9, and Arjun and Kabir both to bucket 11. Bucket 11 holds a chain of two entries, Arjun=85 then Kabir=64: a collision.

Example 1 · From key to bucket index

BucketDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class BucketDemo {    static int bucket(String key, int buckets) {        int h = key.hashCode();        int spread = h ^ (h >>> 16);        return spread & (buckets - 1);    }
    public static void main(String[] args) {        String[] names = {"Riya", "Arjun", "Meera", "Kabir"};        int[] marks = {78, 85, 92, 64};
        Map<String, Integer> map = new HashMap<>();        for (int i = 0; i < names.length; i++) {            System.out.println(names[i] + ": hashCode " + names[i].hashCode() + " -> bucket " + bucket(names[i], 16));            map.put(names[i], marks[i]);        }        System.out.println(map);    }}
Output
Riya: hashCode 2547615 -> bucket 9
Arjun: hashCode 63530642 -> bucket 11
Meera: hashCode 74220700 -> bucket 0
Kabir: hashCode 72251349 -> bucket 11
{Meera=92, Riya=78, Arjun=85, Kabir=64}

What this code does

  • bucket does the same maths as HashMap for a table of 16 buckets. A String's hashCode() is the same on every computer, so these numbers are exact.
  • Arjun and Kabir both land in bucket 11: a collision. The map keeps both in that bucket.
  • The map prints its entries bucket by bucket, from bucket 0 upwards. That is where the "random-looking" order of a HashMap comes from.

put and get follow the same four steps. First call key.hashCode() to get an int. Then mix the bits with h ^ (h >>> 16), so the high bits help choose the bucket. Then keep the last 4 bits with hash & (16 - 1), like % 16 but never negative. Last, compare keys inside that bucket with equals().

A new HashMap gets 16 buckets when you first put something in it. An index is a slot number, 0 to 15.

Order of execution

What get(key) does, step by step

Tap the steps in the order map.get("Arjun") does them.

Collisions and chains

A collision happens when two different keys land in the same bucket. It is normal and safe: the bucket keeps both entries in a chain, and equals() tells the keys apart.

There are only 16 buckets but billions of possible hash codes, so two keys sometimes share a bucket. Even different strings can have the same hash code: "Aa" and "BB" both give 2112. Below, the map keeps both.

Example 2 · A collision: two keys with the same hash code

CollisionDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class CollisionDemo {    public static void main(String[] args) {        System.out.println("\"Aa\".hashCode() = " + "Aa".hashCode());        System.out.println("\"BB\".hashCode() = " + "BB".hashCode());
        Map<String, String> codes = new HashMap<>();        codes.put("Aa", "first");        codes.put("BB", "second");
        System.out.println("Size: " + codes.size());        System.out.println("Aa -> " + codes.get("Aa"));        System.out.println("BB -> " + codes.get("BB"));    }}
Output
"Aa".hashCode() = 2112
"BB".hashCode() = 2112
Size: 2
Aa -> first
BB -> second

What this code does

  • Both keys give 2112, so they go to the same bucket. The map keeps both entries in that bucket's chain.
  • get("BB") reaches the bucket and then uses equals to skip Aa. A same hash code never mixes up two different keys.

Example 3 · A tiny hash map, written by hand

SimpleHashMapDemo.javaJava
class Node {    final String key;    int value;    Node next;
    Node(String key, int value, Node next) {        this.key = key;        this.value = value;        this.next = next;    }}
class SimpleHashMap {    private final Node[] table = new Node[4];    private int size;
    private int indexFor(String key) {        return Math.floorMod(key.hashCode(), table.length);    }
    void put(String key, int value) {        int i = indexFor(key);        for (Node n = table[i]; n != null; n = n.next) {            if (n.key.equals(key)) {                n.value = value;                return;            }        }        table[i] = new Node(key, value, table[i]);        size++;    }
    Integer get(String key) {        int i = indexFor(key);        for (Node n = table[i]; n != null; n = n.next) {            if (n.key.equals(key)) {                return n.value;            }        }        return null;    }
    int size() {        return size;    }
    void printBuckets() {        for (int i = 0; i < table.length; i++) {            StringBuilder line = new StringBuilder("bucket " + i + ":");            for (Node n = table[i]; n != null; n = n.next) {                line.append(" ").append(n.key).append("=").append(n.value);            }            System.out.println(line);        }    }}
public class SimpleHashMapDemo {    public static void main(String[] args) {        SimpleHashMap price = new SimpleHashMap();        price.put("Pen", 10);        price.put("Eraser", 15);        price.put("Notebook", 40);        price.put("Stapler", 30);        price.put("Marker", 20);        price.put("Pen", 12);
        price.printBuckets();        System.out.println("Notebook -> " + price.get("Notebook"));        System.out.println("Compass -> " + price.get("Compass"));        System.out.println("Size: " + price.size());    }}
Output
bucket 0: Eraser=15
bucket 1: Stapler=30 Pen=12
bucket 2: Marker=20
bucket 3: Notebook=40
Notebook -> 40
Compass -> null
Size: 5

What this code does

  • This toy map has only 4 buckets and picks one with Math.floorMod(hashCode, 4), a remainder that is never negative. Each bucket holds a chain of Node objects linked by next.
  • put walks the chain and uses equals: for Pen the second time, it finds the key and replaces 10 with 12, so the size stays 5. New keys go to the front of the chain (the real HashMap adds them at the end).
  • get("Compass") checks one short chain and returns null. It never looks at the other buckets.

A bucket therefore holds a small chain: a linked list of entries. get walks the chain and uses equals() to find the right key. With few entries per bucket, that walk is very short, so get and put take constant time on average, written O(1). The second example builds a tiny hash map by hand, so you can see the chains.

Since Java 8, a chain that grows to 8 entries is turned into a small sorted tree (once the table has at least 64 buckets). Then even a crowded bucket is searched in O(log n) instead of O(n).

Load factor and resizing

The load factor is how full a HashMap may get before it grows; the default is 0.75. With 16 buckets, the 13th entry passes the limit, so the map resizes: it builds a table twice as big and moves every entry to its new bucket.

If buckets get crowded, chains get long. With 16 buckets the limit is 16 × 0.75 = 12 entries. Below, two keys are printed, then eleven more are added and the table grows to 32 buckets.

A table of 16 buckets with 12 filled is 75 percent full. The 13th entry goes over the limit, so the map builds a table of 32 buckets and moves every entry. Afterwards 13 of 32 buckets are filled.

Example 4 · Resizing can change the order

ResizeOrderDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class ResizeOrderDemo {    public static void main(String[] args) {        Map<Integer, String> seats = new HashMap<>();        seats.put(20, "Riya");        seats.put(5, "Arjun");        System.out.println("16 buckets: " + seats.keySet());
        for (int seat = 100; seat <= 110; seat++) {            seats.put(seat, "Guest");        }        System.out.println("Size " + seats.size() + ", 32 buckets: " + seats.keySet());    }}
Output
16 buckets: [20, 5]
Size 13, 32 buckets: [100, 5, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 20]

What this code does

  • An Integer's hash code is the number itself. With 16 buckets, 20 goes to bucket 4 and 5 to bucket 5, so 20 is printed first.
  • The 13th entry is more than 12 (16 × 0.75), so the table grows to 32 buckets. Now 5 stays in bucket 5 but 20 moves to bucket 20, and the order of the two keys flips.

The resize is slow for that one put, but it happens rarely, so put is still O(1) on average. Because entries move, the loop order of a HashMap can change after a resize.

Predict the output

When does the table grow?

A new HashMap has 16 buckets and load factor 0.75. Pick the right answer.

Round 1 of 3

Twelve entries are put.

Map<Integer, String> m = new HashMap<>();
for (int i = 1; i <= 12; i++) {
m.put(i, "x");
}
// how many buckets now?
If you know you will store about 1,000 entries, new HashMap<>(2000) starts big and skips several resizes. The size is rounded up to a power of two (here 2048).

Why keys need equals and hashCode

The contract says: if a.equals(b) is true, then a.hashCode() == b.hashCode() must be true too. A HashMap relies on it: an equal key must give the same hash code, so the map looks in the same bucket.

get works only if an equal key gives the same hash code. Below, a plain class and a record are both used as keys, and get is called with a new but equal key object.

Example 5 · Mistake: a key class without equals and hashCode

KeyEqualsDemo.javaJava
import java.util.HashMap;import java.util.Map;
class PlainRollNo {    private final String branch;    private final int roll;
    PlainRollNo(String branch, int roll) {        this.branch = branch;        this.roll = roll;    }}
record RollNo(String branch, int roll) {}
public class KeyEqualsDemo {    public static void main(String[] args) {        Map<PlainRollNo, String> plain = new HashMap<>();        plain.put(new PlainRollNo("CSE", 7), "Asha");        plain.put(new PlainRollNo("CSE", 7), "Asha again");        System.out.println("Plain class -> get: " + plain.get(new PlainRollNo("CSE", 7)) + ", size: " + plain.size());
        Map<RollNo, String> rec = new HashMap<>();        rec.put(new RollNo("CSE", 7), "Asha");        rec.put(new RollNo("CSE", 7), "Asha again");        System.out.println("Record -> get: " + rec.get(new RollNo("CSE", 7)) + ", size: " + rec.size());    }}
Output
Plain class -> get: null, size: 2
Record -> get: Asha again, size: 1

What this code does

  • PlainRollNo uses Object's equals and hashCode, which compare identity. Three new objects are three different keys, so the map keeps 2 entries and get finds nothing.
  • A record gets equals and hashCode from its fields. Equal data gives the same bucket and equals is true, so the second put replaces the first, and get works.

If your key class does not override equals and hashCode, Object's versions compare identity (the same object in memory). Then a second new RollNo("CSE", 7) is a different key, so get returns null.

String, Integer and records already have correct equals and hashCode, so they make safe keys.

Why keys should never change

A lost key is an entry whose key changed after put. The key's hash code changed, but the entry stayed in its old bucket, so get looks in another bucket and returns null although the entry is still in the map.

The bucket is chosen once, when the key is put. Below, a list is used as a key and then changed. Watch what get and containsKey say afterwards.

Example 6 · Mistake: changing a key after put

LostKeyDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class LostKeyDemo {    public static void main(String[] args) {        List<String> team = new ArrayList<>();        team.add("Riya");        team.add("Arjun");
        Map<List<String>, Integer> projectMarks = new HashMap<>();        projectMarks.put(team, 92);        System.out.println("Before: " + projectMarks.get(team));
        team.add("Meera");   // the key changes after put
        System.out.println("After: " + projectMarks.get(team));        System.out.println("containsKey: " + projectMarks.containsKey(team));        System.out.println("Size: " + projectMarks.size() + ", map: " + projectMarks);    }}
Output
Before: 92
After: null
containsKey: false
Size: 1, map: {[Riya, Arjun, Meera]=92}

What this code does

  • A list's hashCode() is built from its elements. Adding Meera changes the hash code, but the entry stays in the bucket chosen for the old one.
  • get and containsKey look in the new bucket and find nothing. The entry is still inside (size 1), but no lookup can reach it. Use an immutable key, such as List.copyOf(team) or a record.

So keys should be immutable: once created, they never change. String, Integer and records with immutable fields are good keys. Never use a list or an object with setters as a key.

Find the bug

Find the key that can change

Each snippet loses an entry later. Tap the risky line, then check the fix.

Store a team under a list key, then add a member.

Round 1 of 2

Next step

Check your understanding

12 quick questions