What is the minimum number of elements needed to initialize a HashMap without automatic expansion?
sobes.tech AI
Answer from AI
HashMap in Java has an initial capacity and a load factor, defaulting to 16 and 0.75 respectively. Automatic resizing occurs when the number of elements exceeds capacity * load factor.
To avoid automatic resizing during initialization, set the capacity to accommodate the desired number of elements without exceeding the threshold.
The minimum number of elements to initialize a HashMap without resizing is the maximum possible number of elements that do not exceed threshold = capacity * load factor.
For example, with capacity=16 and load factor=0.75, threshold = 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);