HashMap finds a value by its key almost instantly, even with a million entries. How? It does not search the entries one by one. Instead it turns the key into a number, uses that number to pick a bucket, and looks only in that bucket. This lesson opens the box: hash codes, bucket indexes, collisions, the load factor and resizing. You will even build a small hash map of your own, which makes all of it easy to see.
In this lesson you will learn
- How
hashCode()and a bucket index pick where an entry goes - What a collision is, and how chaining handles it
- The load factor and when a map resizes
- How to write a simple hash map from scratch
- Why a bad
hashCode()makes a map slow, but not wrong
You should know HashMap, equals and hashCode and bit manipulation.
From Key to Bucket
Inside, a HashMap is an array of buckets. To store an entry, it follows three steps:
- Call
key.hashCode()to get anint. - Mix the high bits into the low bits with
h ^ (h >>> 16), so keys that differ only in their high bits still spread out. - Keep only the low bits with
& (capacity - 1). Because the capacity is always a power of two, this gives the same result as a remainder, but faster.
public class Main {
// The same steps java.util.HashMap uses to choose a bucket
static int spread(Object key) {
int h = key.hashCode();
return h ^ (h >>> 16); // mix the high bits into the low bits
}
static int bucket(Object key, int capacity) {
return spread(key) & (capacity - 1); // same as mod when capacity is a power of two
}
public static void main(String[] args) {
String[] keys = {"Dhaka", "Khulna", "Sylhet", "Rangpur", "Barishal", "Cumilla"};
System.out.println("key hashCode bucket(16)");
for (String k : keys) {
System.out.printf("%-9s %11d %2d%n", k, k.hashCode(), bucket(k, 16));
}
System.out.println();
System.out.println("\"Aa\".hashCode() = " + "Aa".hashCode());
System.out.println("\"BB\".hashCode() = " + "BB".hashCode() + " <- same hash: a collision");
System.out.println();
int capacity = 16;
double loadFactor = 0.75;
for (int step = 0; step < 4; step++) {
System.out.printf("capacity %3d holds up to %3d entries before resizing%n",
capacity, (int) (capacity * loadFactor));
capacity *= 2;
}
}
}
Output
key hashCode bucket(16)
Dhaka 65994323 13
Khulna -2048141945 12
Sylhet -1803681103 15
Rangpur -1652314683 6
Barishal -1680869098 9
Cumilla -1508253069 10
"Aa".hashCode() = 2112
"BB".hashCode() = 2112 <- same hash: a collision
capacity 16 holds up to 12 entries before resizing
capacity 32 holds up to 24 entries before resizing
capacity 64 holds up to 48 entries before resizing
capacity 128 holds up to 96 entries before resizing
- The hash codes are large numbers, some negative. The bucket index is always between 0 and 15.
"Aa"and"BB"have the same hash code, 2112. Two different keys with the same bucket are a collision. Collisions are normal, and the map must handle them.- The default capacity is 16 and the default load factor is 0.75. When the map holds more than 16 × 0.75 = 12 entries, it doubles to 32 buckets and moves every entry to its new bucket.
Build a Tiny HashMap
Our SimpleMap uses separate chaining: each bucket holds a small linked list of nodes. Java’s real HashMap works the same way, with some extra speed tricks.
import java.util.*;
public class Main {
// A tiny hash map with separate chaining, to show how buckets work
static class SimpleMap<K, V> {
private static class Node<K, V> {
final K key; V value; Node<K, V> next;
Node(K key, V value, Node<K, V> next) { this.key = key; this.value = value; this.next = next; }
}
private Node<K, V>[] table;
private int size;
@SuppressWarnings("unchecked")
SimpleMap(int capacity) { table = (Node<K, V>[]) new Node[capacity]; }
private int index(Object key) {
int h = key.hashCode();
return (h ^ (h >>> 16)) & (table.length - 1);
}
void put(K key, V value) {
int i = index(key);
for (Node<K, V> n = table[i]; n != null; n = n.next) {
if (n.key.equals(key)) { n.value = value; return; } // replace
}
table[i] = new Node<>(key, value, table[i]); // add at head of chain
size++;
if (size > table.length * 3 / 4) resize();
}
V get(K key) {
for (Node<K, V> n = table[index(key)]; n != null; n = n.next) {
if (n.key.equals(key)) return n.value;
}
return null;
}
@SuppressWarnings("unchecked")
private void resize() {
Node<K, V>[] old = table;
table = (Node<K, V>[]) new Node[old.length * 2];
size = 0;
for (Node<K, V> head : old)
for (Node<K, V> n = head; n != null; n = n.next) put(n.key, n.value);
System.out.println(" resized to " + table.length + " buckets");
}
void show() {
for (int i = 0; i < table.length; i++) {
StringBuilder sb = new StringBuilder();
for (Node<K, V> n = table[i]; n != null; n = n.next) sb.append(n.key).append("=").append(n.value).append(" -> ");
if (sb.length() > 0) System.out.println(" bucket " + i + ": " + sb + "null");
}
}
}
// A key with a terrible hashCode: every key lands in the same bucket
record BadKey(String name) {
@Override public int hashCode() { return 1; }
}
public static void main(String[] args) {
SimpleMap<String, Integer> pop = new SimpleMap<>(4);
pop.put("Dhaka", 102);
pop.put("Sylhet", 35);
pop.put("Barishal", 24);
pop.put("Dhaka", 103); // same key: value replaced, size unchanged
System.out.println("4 buckets, 3 entries:");
pop.show();
System.out.println("put Khulna (4th entry is more than 3/4 full):");
pop.put("Khulna", 23);
pop.show();
System.out.println("get(Dhaka) = " + pop.get("Dhaka") + ", get(Pabna) = " + pop.get("Pabna"));
Map<BadKey, Integer> bad = new HashMap<>();
for (int i = 0; i < 5; i++) bad.put(new BadKey("k" + i), i);
System.out.println("Bad keys still work: get(k3) = " + bad.get(new BadKey("k3"))
+ ", but all 5 share one bucket");
}
}
Output
4 buckets, 3 entries:
bucket 1: Barishal=24 -> Dhaka=103 -> null
bucket 3: Sylhet=35 -> null
put Khulna (4th entry is more than 3/4 full):
resized to 8 buckets
bucket 1: Barishal=24 -> null
bucket 4: Khulna=23 -> null
bucket 5: Dhaka=103 -> null
bucket 7: Sylhet=35 -> null
get(Dhaka) = 103, get(Pabna) = null
Bad keys still work: get(k3) = 3, but all 5 share one bucket
- With 4 buckets, Dhaka and Barishal both land in bucket 1, so they share a chain.
getwalks the chain and usesequalsto find the right key. - Putting Dhaka a second time finds the existing node and replaces the value 102 with 103. The size does not grow.
- The fourth entry makes the map more than three-quarters full, so it resizes to 8 buckets. After rehashing, every city has its own bucket, and chains are short again.
get("Pabna")checks one bucket, finds no match and returnsnull.BadKeyreturns 1 fromhashCode()for every key. The realHashMapstill gives correct answers, becauseequalsdecides the match. But every key is in one bucket, so a lookup has to check them one by one.
| Situation | Time for get and put |
|---|---|
| Good hash codes, short chains | O(1) on average |
| Many keys in one bucket (list) | O(n) |
| Many keys in one bucket, Java 8+ (tree) | O(log n) if keys are Comparable |
| Resize | O(n) once, but rare, so still O(1) on average |
Since Java 8, when one bucket’s chain grows past 8 nodes in a large map, HashMap turns that chain into a small balanced tree. This limits the damage from bad or deliberately clashing keys.
Common Mistakes
- Overriding
equalsbut nothashCode. Two equal keys land in different buckets, andgetfails to find them. - Changing a key after putting it in a map. Its hash code changes, so it is now in the wrong bucket and cannot be found. Use immutable keys such as
Stringor records. - Thinking a collision means data is lost. Both entries are kept in the chain.
- Expecting a
HashMapto keep insertion order. Order depends on buckets; useLinkedHashMapif order matters. - Growing a huge map one entry at a time. If you know the size, create it with enough capacity to avoid repeated resizing.
Practice Exercises
Exercise 1. A map has 64 buckets and the default load factor. How many entries can it hold before it resizes, and how many buckets will it have after?
Show answer
64 × 0.75 = 48 entries. Adding the 49th makes it resize to 128 buckets.
Exercise 2. A key’s mixed hash is 45 and the map has 16 buckets. Which bucket does it go to?
Show answer
45 & 15 keeps the lowest 4 bits. 45 in binary is 101101, and the lowest 4 bits are 1101, which is 13. That is the same as 45 % 16.
Frequently Asked Questions
How does HashMap handle collisions in Java?
Entries that land in the same bucket are kept together in a linked list, and equals is used to find the right key. Since Java 8, a very long list in a large map is turned into a balanced tree so lookups stay fast.
Why is HashMap capacity always a power of two?
With a power of two, the bucket index can be found with a fast bitwise AND of the hash and capacity minus one, instead of a slower remainder. HashMap rounds any capacity you ask for up to the next power of two.
Summary
- A
HashMapis an array of buckets; the key’s hash picks the bucket. - Bucket index = mixed hash & (capacity − 1).
- Collisions are stored in chains;
equalsfinds the right key. - Above the load factor (0.75), the map doubles and rehashes.
- Good, stable hash codes keep
getandputat O(1) on average.
Next: Java String Coding Problems.
