Sobes.tech
Middle

Can a HashMap decrease in size?

sobes.tech AI

Answer from AI

Yes. When the number of elements in a Map becomes significantly lower than the shrink threshold, the size of the internal array (table) can be decreased. This occurs in Java 8 and later versions when elements are removed.

The shrink threshold is calculated as: shrink threshold = table.length / 2. The resize threshold is loadFactor * table.length.

When an element is removed, if the current number of elements (size) is less than the shrink threshold and also less than the resize threshold, the size of the internal array is decreased.

// Example logic (simplified)
// The internal method java.util.HashMap#removeNode is conceptually represented
if (currentNode.hash == hash && ((k = currentNode.key) == key || (key != null && key.equals(k)))) {
    // ... node removal ...
    if (--size < (table.length / 2) && size < (int)(loadFactor * table.length)) {
        // size decreased and is below the shrink threshold and the resize threshold
        resize();
    }
    // ...
}

// Method java.util.HashMap#resize (simplified)
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    // ... logic to determine new size (newCap) ...

    // If the current table size is greater than the minimum size (16),
    // and the number of elements has become less than the shrink threshold
    if (oldCap > MINIMUM_CAPACITY && size < (oldCap / 2)) {
        newCap = oldCap / 2; // Halve the size of the internal array
    } else if (oldCap > 0) {
        newCap = oldCap * 2; // Normal increase in size
    }
    // ... rehashing elements into the new table ...
}

It is important to note that shrinking occurs only when methods that modify the HashMap's contents, such as remove(), are called. Simply releasing references to objects stored in the HashMap does not cause it to shrink.