How and when does the increase in the number of buckets in HashMap occur?
sobes.tech AI
Answer from AI
The increase in the number of buckets in a HashMap (a process called resizing or rehashing) occurs when a new element is added, and the current number of elements (size) exceeds the product of the capacity (capacity) and the load factor (loadFactor).
By default, the initial capacity is 16, and the load factor is 0.75.
The formula for determining the threshold value is: threshold = capacity * loadFactor.
When size > threshold, the HashMap creates a new array of buckets, usually with double the capacity, and moves all elements from the old buckets to the new ones. This process can be time-consuming and resource-intensive, especially for large maps.
During the transfer of elements, a new bucket index is calculated for each element using the new capacity.
// Example where resizing might occur
Map<String, Integer> map = new HashMap<>(10, 0.8f); // initial capacity 10, loadFactor 0.8
// threshold = 10 * 0.8 = 8
map.put("one", 1); // size = 1
map.put("two", 2); // size = 2
// ...
map.put("eight", 8); // size = 8. At the next put, size will become 9
map.put("nine", 9); // size = 9. Since 9 > 8, resizing occurs.
// New capacity will be 20, threshold = 20 * 0.8 = 16