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 HashMap stores its entries in an array called the table. Each slot is a bucket that holds the entries whose keys map to that index. To find a key, the map computes the key's hashCode(), turns it into an index, goes straight to that bucket, and compares the keys there with equals. If every bucket holds only one or two entries, get and put take the same time however large the map is.

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 (length - 1) & hash, which keeps the low bits of the hash. Before that, the map mixes the high bits into the low ones with h ^ (h >>> 16), so that hash codes that differ only in their high bits still spread over the table.
  • Entries in the same bucket form a linked list of Node 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 of TreeNodes, so a bad hash degrades to O(log n) instead of O(n).
  • When the number of entries exceeds capacity × loadFactor (0.75 by default), the table doubles and every entry is moved to its new bucket.
HashMap constants and their effect
SettingValueEffect
Default initial capacity16Table length after the first put
Default load factor0.75Resize when size exceeds 75% of the length
TREEIFY_THRESHOLD8A bucket longer than this becomes a tree
MIN_TREEIFY_CAPACITY64Below this table length, the map resizes instead of building a tree
UNTREEIFY_THRESHOLD6A 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 and is only for demonstration.

From hashCode to bucket

The program applies the same spreading and masking steps as HashMap to a few keys for a 16-slot table. Aa and BB are included because they are a famous pair of strings with the same hash code.

Java
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:

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 ints; the bucket is just their low four bits after spreading, so it ranges from 0 to 15.
  • Different hash codes can still share a bucket: plum, Aa and BB all landed in bucket 0. The map handles this by comparing the stored hash and then calling equals on each key in the bucket.
  • Aa and BB 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.

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.

Java
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:

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 put allocates 16 slots.
  • 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.
  • new HashMap<>(100) means "a table of at least 100 slots", rounded up to 128, which holds 96 entries before resizing. HashMap.newHashMap(100), added in Java 19, means "room for 100 entries" and chose 256. When you know the number of entries, use newHashMap.
  • A HashMap never shrinks its table when entries are removed.

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 Comparable, which lets a tree bucket order them. The program prints the table length and the type of the bucket's first node after each put.

Java
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:

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 Nodes.
  • Adding the 9th made the chain longer than the threshold, but the table had only 16 slots, below MIN_TREEIFY_CAPACITY. The map resized to 32 instead, hoping to spread the keys. The 10th entry triggered another resize to 64.
  • With 64 slots, the 11th entry converted the bucket into a tree of TreeNodes. Lookups in that bucket now take about log2(n) comparisons instead of n.

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 keys, and with a constant hash code on keys that cannot be compared.

Java
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):

Output
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 Comparable keys, the tree bucket keeps lookups at O(log n), so the map was only modestly slower than with a good hash.
  • Without Comparable, 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.
  • A good hashCode combines all the fields that equals uses, as records and Objects.hash do. A constant or nearly constant hash code turns a hash map into a list.

Mutable keys

A key's hash code decides which bucket it goes into. The program puts a mutable Point into a map and then changes the point's coordinates, as code that reuses objects might.

Java
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:

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 get(p) looks in the wrong place and returns null, even though p is the very object that was stored.
  • 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 size() is 1 and containsValue finds the value by scanning. The entry is effectively lost.
  • Use immutable keys, such as String, the number wrappers, records with immutable fields, or enums. If a key must change, remove it, change it, and put it back.

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.

Java
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;
    }
}
Output
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 Integer'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 all 0001.
  • Eight more keys pushed the size past 12 and the table doubled to 32. Bucket 1 split in two: [1, 33, 65] stayed at index 1 and [17, 49] moved to index 17.
  • The deciding bit is the one worth 16, the old table length. Keys with hash & 16 equal to 0 stayed, and keys with 16 moved up by exactly 16. The resize method in the JDK 21 source tests (e.hash & oldCap) == 0 to build the two lists.
  • 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 transfer method instead inserted each moved entry at the head of its new chain, which reversed the chains on every resize.
  • A null key was accepted and stored in bucket 0, because HashMap defines the hash of null as 0. Only one null key can exist, and get(null) found it.

Since a resize touches every entry once, presizing a map that will hold a known number of entries, with HashMap.newHashMap(n), skips all of these copies.

Rules that follow from the design

Using HashMap well
RuleReason
Override equals and hashCode togetherEqual keys must land in the same bucket
Use all equals fields in hashCodeKeeps buckets short
Make keys immutableA changed hash code loses the entry
Make key classes Comparable if collisions are possibleTree buckets can then search in O(log n)
Presize with HashMap.newHashMap(n)Avoids repeated resizing
Leave the load factor at 0.75Lower wastes memory, higher lengthens buckets
Use ConcurrentHashMap across threadsHashMap is not thread-safe; see ConcurrentHashMap
Use LinkedHashMap or TreeMap for orderIteration order depends on hashes and table size; see TreeMap and LinkedHashMap