HashMap internals · Topic 4 of 6
Capacity and load factor
Definition​
A HashMap starts with 16 buckets and grows (doubles) when it is more than 75% full, which is its load factor. Growing means rebuilding the table, so if you know how many entries are coming, create the map with the right size from the start.
Example code​
Sizing a map for 1,000 entries without resizing
import java.util.HashMap;
import java.util.Map;
class Demo {
public static void main(String[] args) {
int expected = 1_000;
// new HashMap<>(1000) is NOT enough: it rounds up to 1024 buckets and resizes at 768 entries
int needed = (int) Math.ceil(expected / 0.75); // entries / load factor
System.out.println("buckets needed: " + needed + " (rounded up to a power of two: 2048)");
Map<Integer, String> sized = HashMap.newHashMap(expected); // Java 19+: does that maths for you
for (int i = 0; i < expected; i++) sized.put(i, "value " + i); // no resize while filling
System.out.println(sized.size());
}
}
// Output:
// buckets needed: 1334 (rounded up to a power of two: 2048)
// 1000
Finished this page? Track your progress (saved only in your browser).