Sobes.tech
Junior — Middle

Kui palju elemente on vaja HashMap-i automaatse laienemise vältimiseks?

sobes.tech AI

Vastus AI-lt

Java HashMap has an initial capacity and a load factor, which are by default 16 and 0.75 respectively. Automatic resizing occurs when the number of elements exceeds capacity * load factor.

To avoid automatic resizing during initialization, set a capacity that can hold the required number of elements without exceeding the threshold.

The minimum number of elements to initialize a HashMap without resizing is the maximum possible number that does not exceed the threshold = capacity * load factor.

For example, with capacity=16 and load factor=0.75, the threshold is 12. This means that adding up to 12 elements will not trigger resizing.

If you want to initialize a HashMap with a specific number of elements n without resizing, set initialCapacity >= n / loadFactor.

Example:

int expectedElements = 10;
float loadFactor = 0.75f;
int initialCapacity = (int) Math.ceil(expectedElements / loadFactor);
HashMap<String, String> map = new HashMap<>(initialCapacity, loadFactor);