man java/hashmap
How Java's HashMap works: buckets, treeification and hash spreading
Why does a Java HashMap of Integer keys print them in an order that
follows the numbers’ low bits, the same order on every run, when the
documentation promises no order at all?
var m = new HashMap<Integer, Integer>();
for (int k : List.of(70, 3, 65541, 17, 1000, 5, 42)) {
m.merge(k, 1, Integer::sum);
}
System.out.println(m.keySet());
$ java Order.java; java Order.java
[17, 3, 65541, 5, 70, 1000, 42]
[17, 3, 65541, 5, 70, 1000, 42]
This article reads java/util/HashMap.java and java/lang/Integer.java from
openjdk/jdk27u at the tag jdk-27.0.1.1-ga, the tag the Homebrew formula
builds, and checks them with small programs run on that build (OpenJDK
27.0.1.1) on an Apple M2 Pro. Some experiments read the private table field
through reflection, which needs --add-opens java.base/java.util=ALL-UNNAMED.
The short version
A HashMap is an array of buckets whose length is a power of two. Each
bucket is a singly linked list of nodes, and each node stores the key’s hash,
the key, the value and the next node. The bucket for a key is its spread hash
masked by the table length. When the map holds more than three quarters of
the table length, the table doubles. When one bucket’s list grows past eight
nodes and the table has at least 64 buckets, that bucket becomes a red-black
tree. Nothing in this involves a random seed, so the layout, and with it the
iteration order, depends only on the keys and the order they arrived in.
Buckets and nodes
The fields are a few lines
(L390,
L421-L428):
transient Node<K,V>[] table, an int threshold and a final float loadFactor. The table is allocated on first use. A Node
(L281-L318)
has four fields: final int hash, final K key, V value and Node<K,V> next.
table (length 16)
+----+----+----+----+----+-- ... --+----+
| | o | | o | | | |
+----+-|--+----+-|--+----+-- ... --+----+
| |
v v
Node Node Node = { hash, key, value, next }
hash 17 hash 3
key 17 key 3
|
v
Node
hash 33
key 33
Every node is its own object, and so are the key and the value. A map from
Integer to Integer can cost three objects per entry: the node, the key and
the value, unless the boxes come from the cache described below. Storing the
hash in the node means a lookup compares hashes first and calls equals only
when they match, and resizing never calls hashCode again.
putVal
(L657-L701)
picks the bucket with (n - 1) & hash, where n is the table length. If the
bucket is empty the new node goes there. Otherwise it walks the list and
either finds the key and replaces the value, or appends a new node at the
end
(L674).
Hash spreading
Masking with n - 1 keeps only the low bits of the hash. Keys whose hashes
differ only in the high bits would all land in one bucket. So HashMap never
uses hashCode() directly
(L336-L339):
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
The top 16 bits are XORed into the bottom 16. The comment above it
(L321-L335)
calls this the cheapest possible way to “reduce systematic lossage”, gives
Float keys holding consecutive whole numbers as the known bad case, and
leaves the rest to the tree bins. A null key hashes to 0 and lives in
bucket 0.
For Integer the input is trivial. Integer.hashCode() calls
Integer.hashCode(int value), which is return value;
(Integer.java L1117-L1132).
Twelve keys of the form i << 16 have hashes whose low 16 bits are all zero.
Without spreading they would share bucket 0 of a 16-bucket table:
var m = new HashMap<Integer, String>();
for (int i = 0; i < 12; i++) {
m.put(i << 16, "x");
}
// count the non-null slots of the private table field
$ java --add-opens java.base/java.util=ALL-UNNAMED Spread.java
12 keys of the form i << 16: table 16, 12 bins used
without spreading, (i << 16) & 15 is 0 for every i
[0, 65536, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896]
After the XOR, i << 16 becomes (i << 16) ^ i, so key i lands in bucket
i. That also explains the opening example. Keys below 65,536 are their own
spread hash, so key k lands in bucket k & 15, and iteration walks the
buckets from 0 up: 17 (bucket 1), 3, 65541 (its hash is 65541 XOR 1, bucket
4), 5, 70 (bucket 6), 1000 (bucket 8), 42 (bucket 10). There is no seed
anywhere, so a run of the same program gives the same order. The class
documentation makes no promise about order, so the next release could change
it.
Growing
The defaults are a 16-bucket table and a load factor of 0.75
(L238-L250).
putVal calls resize() when the size passes threshold, which is
capacity times load factor. Printing the table length whenever it changes:
$ java --add-opens java.base/java.util=ALL-UNNAMED Growth.java
size 1: table 16
size 13: table 32
size 25: table 64
size 49: table 128
...
size 12289: table 32768
size 24577: table 65536
size 49153: table 131072
newHashMap(50_000): table 131072
The 13th key doubles the table because 12 is three quarters of 16.
resize()
(L709-L780)
uses a neat property of power-of-two tables. When the length doubles from
oldCap to 2 * oldCap, a node in bucket j either stays in j or moves
to j + oldCap, decided by the single bit hash & oldCap. So each chain is
split into a “lo” list and a “hi” list in one pass, keeping the nodes in
their old relative order, without calling hashCode or equals once.
Java 19 added HashMap.newHashMap(int numMappings)
(L2589-L2611).
It divides by the load factor first, so newHashMap(50_000) asks for
66,667 slots and gets 131,072. The older constructor new HashMap<>(50_000)
takes a capacity and gets 65,536 slots, and would still resize once after
49,152 entries.
Treeification
A bad hashCode can put every key in one bucket, and then every lookup walks
a list of all of them. Since Java 8 (JEP 180) a long bucket becomes a
red-black tree. Three constants control it
(L252-L275):
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
The documentation says a bin is converted “when adding an element to a bin
with at least this many nodes”. treeifyBin
(L787-L790)
checks the table first: below 64 buckets it resizes instead, on the theory
that a small table is the problem. A resize split can turn a tree back into
a list when one of its halves has 6 nodes or fewer
(split, L2323).
To see it, I made a key type whose hashCode is always 42 and watched the
head of bucket 42:
record Key(int id) implements Comparable<Key> {
@Override public int hashCode() { return 42; }
@Override public int compareTo(Key o) { return Integer.compare(id, o.id); }
}
$ java --add-opens java.base/java.util=ALL-UNNAMED Treeify.java
put 1 keys: table 64, bin head Node
...
put 8 keys: table 64, bin head Node
put 9 keys: table 64, bin head TreeNode
...
merge 7 keys: table 64, bin head Node
merge 8 keys: table 64, bin head TreeNode
...
default map, 8 keys: table 16, bin head Node
default map, 9 keys: table 32, bin head Node
default map, 10 keys: table 64, bin head Node
default map, 11 keys: table 64, bin head TreeNode
With put, the ninth colliding key makes the tree, as documented. With
merge the eighth one does. putVal starts counting at the second node of
the chain, and merge counts every node it walks; both then test
binCount >= TREEIFY_THRESHOLD - 1
(L675,
L1436).
A map created with the default 16 buckets doubles twice, at 9 and 10 keys,
before the 11th key finally makes a tree.
A tree bin needs an order. TreeNode
(L1992)
orders by hash first. When hashes tie and both keys are of the same class
C implements Comparable<C>, it uses compareTo. When even that fails,
tieBreakOrder
(L2084-L2091)
compares class names and then System.identityHashCode, only to keep
insertion consistent. A lookup can’t reproduce that last step, so when
hashes tie and compareTo doesn’t help, find
(L2043-L2068)
searches the right subtree recursively and then the left. The implementation notes
(L146-L232)
say the worst case becomes O(log n) “so long as they are also Comparable”.
Tree bins are rare with a decent hash. The same notes give the expected
share of buckets holding k nodes at the default load factor, a Poisson
distribution with a mean of about 0.5: 0.6065 for an empty bucket, 0.0758
for two nodes, and 0.00000006 for eight. A TreeNode is “about twice the
size” of a Node. It extends LinkedHashMap.Entry and adds parent, left,
right and prev links plus a colour bit.
merge, and where it puts new keys
map.merge(key, 1, Integer::sum) is the counting idiom since Java 8. In
HashMap it is its own method
(L1386-L1440)
that hashes once, walks the bucket once, and either applies the function to
the old value or inserts. If the function returns null the key is removed.
It resizes before searching, when the size is already over the threshold,
where putVal resizes after inserting. And it inserts the new node at the
head of the bucket:
tab[i] = newNode(hash, key, value, first);
(L1435).
So two maps holding the same colliding keys can list them in different
orders, depending on whether they were filled with put or merge. Keys 1,
17 and 33 all land in bucket 1 of a 16-bucket table:
var put = new HashMap<Integer, Integer>();
var merged = new HashMap<Integer, Integer>();
for (int k : List.of(1, 17, 33)) { // all three land in bucket 1 of 16
put.put(k, 1);
merged.merge(k, 1, Integer::sum);
}
System.out.println("put: " + put.keySet());
System.out.println("merge: " + merged.keySet());
System.out.println(put.equals(merged));
$ java PutMerge.java
put: [1, 17, 33]
merge: [33, 17, 1]
true
Boxing
A HashMap holds objects, so int keys and values are boxed.
Integer.valueOf
(L988-L992)
returns a shared object from IntegerCache for -128 to 127 and allocates a
new one for anything else. The low end is fixed at -128. The high end
defaults to 127, and the comment above the cache says the
-XX:AutoBoxCacheMax=<size> option controls it
(L879-L923):
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println((a == b) + " " + (c == d) + " " + c.equals(d));
$ java Cache.java
true false true
$ java -XX:AutoBoxCacheMax=1000 Cache.java
true true true
So a counter that uses merge(n, 1, Integer::sum) takes each new count’s
box from the cache up to 127, and allocates one Integer per increment after
that.
Curious facts
- With colliding keys,
mergeturns a bucket into a tree at its eighth node andputat its ninth, because the two methods count the chain differently. - A default-size
HashMapresizes twice because of one crowded bucket before it builds a tree: 16 to 32 to 64 buckets, then a tree at 11 keys. HashMaphas no per-process hash seed. A map ofIntegerkeys smaller than its table iterates them in ascending order ofkey & (length - 1), on every run.- The
IntegerCachecomment warns that the cache “is archived with CDS and reloaded from the shared archive at runtime”. The 256 cachedIntegerobjects can be loaded from the class-data sharing archive instead of being built at startup (L888-L893). -XX:AutoBoxCacheMaxcan raise the cache’s upper end but not lower it: the code takesMath.maxof the setting and 127 (L916).
History
- 1.2:
HashMaparrives with the Collections Framework (@since 1.2). - 5.0:
Integer.valueOf(int)and its cache (@since 1.5). - 8: JEP 180 replaces long chains with balanced trees in
HashMapandLinkedHashMap, and leavesHashtableandWeakHashMapas they were.Map.mergearrives (@since 1.8). - 19:
HashMap.newHashMap(int)(JDK-8186958).
Sources
java/util/HashMap.javaatjdk-27.0.1.1-gain openjdk/jdk27u: implementation notes, constants, Node, hash(), putVal, resize, treeifyBin, merge, TreeNode, tieBreakOrder, split, newHashMapjava/lang/Integer.javaat the same tag: IntegerCache, valueOf, hashCode- JEP 180: Handle Frequent HashMap Collisions with Balanced Trees
- JDK-8186958: Need method to create pre-sized HashMap
- Homebrew formula building the tag: openjdk.rb
grep -rl /lib/java/hashmap/
ls java/
- draft Why Java sorts ints and objects differentlyArrays.sort(int[]) runs a dual-pivot quicksort with insertion-sort, run-merging and heap-sort fallbacks, while Arrays.sort(Object[]) and List.sort run TimSort: what each does in OpenJDK 27, why stability decides which one you get, and what the difference costs.