How HashMap Works Internally
A HashMap finds a key in roughly constant time by turning its hashCode into an index in an array of buckets. Collisions, resizing and the equals contract decide whether that stays true. This page follows a key from hashCode to bucket, watches the table grow, shows a crowded bucket turning into a tree, measures what a bad hashCode costs, and breaks a map with a mutable key.
Contents
The structure: an array of buckets
A HashMaphashCode()equalsgetput
The details, as implemented in OpenJDK since Java 8:
- The table length is always a power of two, starting at 16, and the table is only allocated on the first
.put - The index is
, which keeps the low bits of the hash. Before that, the map mixes the high bits into the low ones with(length - 1) & hash , so that hash codes that differ only in their high bits still spread over the table.h ^ (h >>> 16) - Entries in the same bucket form a linked list of
objects. When a bucket grows past 8 entries and the table has at least 64 slots, the list is converted into a red-black tree ofNode s, so a bad hash degrades to O(log n) instead of O(n).TreeNode - When the number of entries exceeds
(0.75 by default), the table doubles and every entry is moved to its new bucket.capacity × loadFactor
| Setting | Value | Effect |
|---|---|---|
| Default initial capacity | 16 | Table length after the first put |
| Default load factor | 0.75 | Resize when size exceeds 75% of the length |
TREEIFY_THRESHOLD | 8 | A bucket longer than this becomes a tree |
MIN_TREEIFY_CAPACITY | 64 | Below this table length, the map resizes instead of building a tree |
UNTREEIFY_THRESHOLD | 6 | A tree with this many or fewer entries becomes a list again |
The tree buckets arrived in Java 8 (JEP 180). The programs below ran on JDK 21; two of them read private fields through reflection to show the table, which needs --add-opens java.base/java.util=ALL-UNNAMED
From hashCode to bucket
The program applies the same spreading and masking steps as HashMapAaBB
public class BucketIndex {
// The same two steps 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 tableLength) {
return (tableLength - 1) & spread(key); // same as a modulo, for powers of two
}
public static void main(String[] args) {
System.out.printf("%-8s %12s %8s%n", "key", "hashCode", "bucket");
for (String k : new String[] {"apple", "pear", "plum", "Aa", "BB", "fig"}) {
System.out.printf("%-8s %12d %8d%n", k, k.hashCode(), bucket(k, 16));
}
// "Aa" and "BB" have the same hashCode, so they always share a bucket
boolean same = "Aa".hashCode() == "BB".hashCode();
System.out.println("Aa and BB share a hashCode: " + same);
}
}
Output:
key hashCode bucket
apple 93029210 1
pear 3436774 2
plum 3444116 0
Aa 2112 0
BB 2112 0
fig 101380 5
Aa and BB share a hashCode: true
- Hash codes are large, arbitrary
s; the bucket is just their low four bits after spreading, so it ranges from 0 to 15.int - Different hash codes can still share a bucket:
,plum andAa all landed in bucket 0. The map handles this by comparing the stored hash and then callingBB on each key in the bucket.equals andAa have exactly the same hash code, 2112, so no table size can separate them. Collisions like this are normal; what matters is that they are rare.BB
Watching the table grow
The program puts 100 entries into a default map and prints the table length each time it changes, then compares two ways of presizing.
import java.lang.reflect.Field;
import java.util.HashMap;
// Run with: java --add-opens java.base/java.util=ALL-UNNAMED ResizeWatch
public class ResizeWatch {
static int tableLength(HashMap<?, ?> map) throws ReflectiveOperationException {
Field table = HashMap.class.getDeclaredField("table");
table.setAccessible(true);
Object[] array = (Object[]) table.get(map);
return array == null ? 0 : array.length;
}
public static void main(String[] args) throws ReflectiveOperationException {
HashMap<Integer, String> map = new HashMap<>();
System.out.println("new HashMap(): table length " + tableLength(map));
int last = -1;
for (int i = 1; i <= 100; i++) {
map.put(i, "v" + i);
int len = tableLength(map);
if (len != last) {
System.out.println("after " + i + " entries: table length " + len);
last = len;
}
}
HashMap<Integer, String> sized = new HashMap<>(100);
sized.put(1, "x");
System.out.println("new HashMap(100), one put: table length " + tableLength(sized));
HashMap<Integer, String> exact = HashMap.newHashMap(100); // Java 19+
exact.put(1, "x");
System.out.println("HashMap.newHashMap(100), one put: table length " + tableLength(exact));
}
}
Output:
new HashMap(): table length 0
after 1 entries: table length 16
after 13 entries: table length 32
after 25 entries: table length 64
after 49 entries: table length 128
after 97 entries: table length 256
new HashMap(100), one put: table length 128
HashMap.newHashMap(100), one put: table length 256
- A new map has no table at all. The first
allocates 16 slots.put - The table doubled when the 13th entry arrived (more than 16 × 0.75 = 12), then at 25, 49 and 97. Each resize allocates a new array and moves every entry, so filling a map from empty does about two moves per entry in total.
means "a table of at least 100 slots", rounded up to 128, which holds 96 entries before resizing.new HashMap<>(100) , added in Java 19, means "room for 100 entries" and chose 256. When you know the number of entries, useHashMap.newHashMap(100) .newHashMap- A
never shrinks its table when entries are removed.HashMap
A crowded bucket becomes a tree
Every key in this program has the same hash code, 42, so all of them go into one bucket. The keys are Comparableput
import java.lang.reflect.Field;
import java.util.HashMap;
public class TreeBins {
// Every key lands in the same bucket, but the keys can be ordered
record Clash(int id) implements Comparable<Clash> {
@Override
public int hashCode() {
return 42;
}
@Override
public int compareTo(Clash o) {
return Integer.compare(id, o.id);
}
}
// Reads the private table; needs --add-opens java.base/java.util=ALL-UNNAMED
static String describe(HashMap<?, ?> map) throws ReflectiveOperationException {
Field f = HashMap.class.getDeclaredField("table");
f.setAccessible(true);
Object[] table = (Object[]) f.get(map);
Object bin = table[42 & (table.length - 1)];
return "size " + map.size() + ", table " + table.length + ", bin type "
+ bin.getClass().getSimpleName();
}
public static void main(String[] args) throws ReflectiveOperationException {
HashMap<Clash, Integer> map = new HashMap<>();
for (int i = 1; i <= 12; i++) {
map.put(new Clash(i), i);
System.out.println("after put " + i + ": " + describe(map));
}
}
}
Output:
after put 1: size 1, table 16, bin type Node
after put 2: size 2, table 16, bin type Node
after put 3: size 3, table 16, bin type Node
after put 4: size 4, table 16, bin type Node
after put 5: size 5, table 16, bin type Node
after put 6: size 6, table 16, bin type Node
after put 7: size 7, table 16, bin type Node
after put 8: size 8, table 16, bin type Node
after put 9: size 9, table 32, bin type Node
after put 10: size 10, table 64, bin type Node
after put 11: size 11, table 64, bin type TreeNode
after put 12: size 12, table 64, bin type TreeNode
- Up to 8 entries, the bucket is a linked list of
s.Node - Adding the 9th made the chain longer than the threshold, but the table had only 16 slots, below
. The map resized to 32 instead, hoping to spread the keys. The 10th entry triggered another resize to 64.MIN_TREEIFY_CAPACITY - With 64 slots, the 11th entry converted the bucket into a tree of
s. Lookups in that bucket now take about log2(n) comparisons instead of n.TreeNode
What a bad hashCode costs
To measure the protection that tree buckets give, the program inserts and looks up 20,000 keys three ways: with a good hash code, with a constant hash code on Comparable
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;
public class BadHashCode {
// Every key lands in the same bucket
record BadKey(int id) {
@Override
public int hashCode() {
return 42;
}
}
// Same bad hash, but Comparable, so a tree bucket can order the keys
record BadComparableKey(int id) implements Comparable<BadComparableKey> {
@Override
public int hashCode() {
return 42;
}
@Override
public int compareTo(BadComparableKey o) {
return Integer.compare(id, o.id);
}
}
record GoodKey(int id) {
}
// Best of 3 runs, each on a fresh HashMap
static <K> double time(IntFunction<K> make, int n) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
Map<K, Integer> map = new HashMap<>();
long start = System.nanoTime();
for (int i = 0; i < n; i++) {
map.put(make.apply(i), i);
}
for (int i = 0; i < n; i++) {
map.get(make.apply(i));
}
best = Math.min(best, System.nanoTime() - start);
}
return best / 1e6;
}
public static void main(String[] args) {
int n = 20000;
System.out.println("20,000 puts and gets, best of 3 runs:");
System.out.printf(" good hashCode: %8.1f ms%n", time(GoodKey::new, n));
System.out.printf(" constant hash, Comparable: %8.1f ms%n",
time(BadComparableKey::new, n));
System.out.printf(" constant hash, no compare: %8.1f ms%n", time(BadKey::new, n));
}
}
Output (best of 3 runs on a 2-CPU Linux machine, JDK 21; the ratios are what matter):
20,000 puts and gets, best of 3 runs:
good hashCode: 7.1 ms
constant hash, Comparable: 11.5 ms
constant hash, no compare: 2959.9 ms
- With a constant hash, every key is in one bucket. For
keys, the tree bucket keeps lookups at O(log n), so the map was only modestly slower than with a good hash.Comparable - Without
, the tree has no order to use, falls back to comparing class names and identity hash codes, and often has to search both subtrees. The map was hundreds of times slower than with a good hash: in effect, every lookup scanned a long list.Comparable - A good
combines all the fields thathashCode uses, as records andequals do. A constant or nearly constant hash code turns a hash map into a list.Objects.hash
Mutable keys
A key's hash code decides which bucket it goes into. The program puts a mutable Point
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MutableKey {
static class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
public static void main(String[] args) {
Map<Point, String> labels = new HashMap<>();
Point p = new Point(1, 2);
labels.put(p, "start");
p.x = 99; // the key changes AFTER it was stored
System.out.println("get(p): " + labels.get(p));
System.out.println("get(new Point(1,2)): " + labels.get(new Point(1, 2)));
System.out.println("size: " + labels.size());
System.out.println("containsValue: " + labels.containsValue("start"));
}
}
Output:
get(p): null
get(new Point(1,2)): null
size: 1
containsValue: true
- After the change, the key's new hash code points to a different bucket, so
looks in the wrong place and returnsget(p) , even thoughnull is the very object that was stored.p - Looking up an equal point with the original coordinates also fails: it reaches the right bucket, but the stored key no longer equals it.
- The entry is still there, so
is 1 andsize() finds the value by scanning. The entry is effectively lost.containsValue - Use immutable keys, such as
, the number wrappers, records with immutable fields, or enums. If a key must change, remove it, change it, and put it back.String
How a resize splits each bucket
Doubling the table does not mean hashing every key again. Because the length is a power of two, doubling it adds exactly one bit to the mask. Each entry either stays at its index or moves to its index plus the old length, depending only on that one bit of its stored hash. The program fills one bucket on purpose and watches it split.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResizeSplit {
public static void main(String[] args) throws ReflectiveOperationException {
Field table = HashMap.class.getDeclaredField("table");
table.setAccessible(true);
// Keys 1, 17, 33 ... share bucket 1 in a 16-slot table (Integer's hash is its value)
Map<Integer, String> map = new HashMap<>();
for (int k : new int[] {1, 17, 33, 49, 65}) {
map.put(k, "v" + k);
}
System.out.println("16 slots: " + buckets(map, (Object[]) table.get(map)));
// Adding more keys pushes the size past 12 and the table doubles to 32
for (int k = 100; k < 108; k++) {
map.put(k, "v" + k);
}
Object[] t = (Object[]) table.get(map);
System.out.println(t.length + " slots: " + buckets(map, t));
for (int k : new int[] {1, 17, 33, 49, 65}) {
System.out.printf(" key %2d: hash & 16 is %2d, so it %s%n", k, k & 16,
((k & 16) == 0) ? "stayed at index 1" : "moved to index 1 + 16 = 17");
}
// A null key is allowed and always goes to bucket 0
map.put(null, "nothing");
System.out.println("null key: get(null) = " + map.get(null) + ", in bucket 0: "
+ bucketKeys((Object[]) table.get(map), 0));
}
static String buckets(Map<Integer, String> map, Object[] t) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < t.length; i++) {
List<Object> keys = bucketKeys(t, i);
if (keys.size() > 1) {
sb.append("index ").append(i).append(' ').append(keys).append(" ");
}
}
return sb.toString().trim();
}
static List<Object> bucketKeys(Object[] t, int i) {
List<Object> keys = new ArrayList<>();
try {
for (Object node = t[i]; node != null; ) {
Field key = node.getClass().getDeclaredField("key");
Field next = node.getClass().getDeclaredField("next");
key.setAccessible(true);
next.setAccessible(true);
keys.add(key.get(node));
node = next.get(node);
}
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
return keys;
}
}
16 slots: index 1 [1, 17, 33, 49, 65]
32 slots: index 1 [1, 33, 65] index 17 [17, 49]
key 1: hash & 16 is 0, so it stayed at index 1
key 17: hash & 16 is 16, so it moved to index 1 + 16 = 17
key 33: hash & 16 is 0, so it stayed at index 1
key 49: hash & 16 is 16, so it moved to index 1 + 16 = 17
key 65: hash & 16 is 0, so it stayed at index 1
null key: get(null) = nothing, in bucket 0: [null]
- An
's hash code is its value, and the spreading step changes nothing for small numbers, so 1, 17, 33, 49 and 65 all ended in bucket 1 of the 16-slot table. Their low four bits are allInteger .0001 - Eight more keys pushed the size past 12 and the table doubled to 32. Bucket 1 split in two:
stayed at index 1 and[1, 33, 65] moved to index 17.[17, 49] - The deciding bit is the one worth 16, the old table length. Keys with
equal to 0 stayed, and keys with 16 moved up by exactly 16. Thehash & 16 method in the JDK 21 source testsresize to build the two lists.(e.hash & oldCap) == 0 - Both halves kept their relative order, 1 before 33 before 65, because the split walks the old list once and appends to the two new ones. The Java 7
method instead inserted each moved entry at the head of its new chain, which reversed the chains on every resize.transfer - A
key was accepted and stored in bucket 0, becausenull defines the hash ofHashMap as 0. Only onenull key can exist, andnull found it.get(null)
Since a resize touches every entry once, presizing a map that will hold a known number of entries, with HashMap.newHashMap(n)
Rules that follow from the design
| Rule | Reason |
|---|---|
Override equalshashCode | Equal keys must land in the same bucket |
Use all equalshashCode | Keeps buckets short |
| Make keys immutable | A changed hash code loses the entry |
Make key classes Comparable | Tree buckets can then search in O(log n) |
Presize with HashMap.newHashMap(n) | Avoids repeated resizing |
| Leave the load factor at 0.75 | Lower wastes memory, higher lengthens buckets |
Use ConcurrentHashMap | HashMap |
Use LinkedHashMapTreeMap | Iteration order depends on hashes and table size; see |