How HashMap works inside
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · From key to bucket index
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); }}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
bucketdoes the same maths asHashMapfor a table of 16 buckets. AString'shashCode()is the same on every computer, so these numbers are exact.ArjunandKabirboth 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
HashMapcomes 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
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")); }}"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 usesequalsto skipAa. A same hash code never mixes up two different keys.
Example 3 · A tiny hash map, written by hand
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()); }}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 ofNodeobjects linked bynext. putwalks the chain and usesequals: forPenthe 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 realHashMapadds them at the end).get("Compass")checks one short chain and returnsnull. 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.
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.
Example 4 · Resizing can change the order
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()); }}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.
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
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()); }}Plain class -> get: null, size: 2 Record -> get: Asha again, size: 1
What this code does
PlainRollNousesObject'sequalsandhashCode, which compare identity. Threenewobjects are three different keys, so the map keeps 2 entries andgetfinds nothing.- A record gets
equalsandhashCodefrom its fields. Equal data gives the same bucket andequalsis true, so the secondputreplaces the first, andgetworks.
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
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); }}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. AddingMeerachanges the hash code, but the entry stays in the bucket chosen for the old one. getandcontainsKeylook 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 asList.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 2Next step
Check your understanding
12 quick questions