Video in progress

Strong Junior 🧺 Collections

What do HashMap's initial capacity and load factor parameters control?

Capacity is the initial length of the bucket array (16 by default), and load factor is how full the array may get before it grows (0.75 by default). When the number of elements exceeds capacity * loadFactor, the array doubles and every entry is redistributed.

📖 Answer

By default it is 16 × 0.75 = 12. When you add the 13th element, a resize happens: 32 buckets, then 64, and so on. Every resize means moving all entries into a new array.

If you know the size in advance, you can avoid this:

// expecting 10,000 entries
Map<Long, User> byId = new HashMap<>(14_000);        // more than 10,000 / 0.75

// easier on Java 19+
Map<Long, User> byId2 = HashMap.newHashMap(10_000);  // computes the right capacity itself

A common mistake in interviews: thinking new HashMap<>(10_000) can hold 10,000 elements. In fact it allocates 16,384 buckets and resizes after about 12,288 elements. That is enough in this case, but with new HashMap<>(1000) and 1000 elements, it still grows after 1024 × 0.75 = 768.

A lower load factor means fewer collisions but more memory. In practice almost nobody changes 0.75.