Open In App

How does HashMap handle resizing when it reaches its capacity in Java?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The capacity of a HashMap simply doubles when it reaches a certain threshold. The threshold depends on the initial capacity and the load factor of the HashMap. Consider Capacity as the number of spaces, a HashMap currently has to store elements and Load factor is a measure of how full the map is allowed to get before its capacity is increased. Size can be understood by the number of elements a HashMap has at a certain point in time or the count of occupied buckets.

How load factor and initial capacity affect resizing in HashMap:

When the entries in the HashMap increase than the product of the current capacity and load factor, the HashMap is rehashed, and the capacity of the map is doubled.

  • Suppose the initial capacity is 8, then as threshold is reached.
  • A new empty array is created with double size (16).
  • Then every key-value pair, the hash code of the key using the new capacity, and the corresponding bucket in a new array.
  • Old values are moved into the new array.

Note: If the load factor is higher, it decreases space overhead but increases lookup cost. Creating a HashMap with sufficiently large storage will allow mapping to be stored much more efficiently with low hashing operations.

Java Program how HashMap handle Resizing after reaching Capacity

There is no official method to check for capacity of a HashMap. We can go through reflection. But it is not recommended. We can see the following code how after reaching threshold (>3 size) the capacity is doubled.

Java
// Java Program to handle resizing in HashMap when it reaches its capacity
import java.lang.reflect.Field;
import java.util.HashMap;

public class Main 
{
    public static void main(String args[]) 
    {
        try {
            HashMap<Integer, Integer> hm = new HashMap<>(4);
            hm.put(1,1);
            hm.put(2,1);
            hm.put(3,1);
              hm.put(4,1);
            // Getting the 'table' field using reflection
            Field tableField = HashMap.class.getDeclaredField("table");
            tableField.setAccessible(true);

            // Accessing the 'table' field of the HashMap instance
            Object[] table = (Object[]) tableField.get(hm);

            // Printing the length of the 'table' array
            System.out.println(table == null ? 0 : table.length);

        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();  // Handle the exception appropriately in your application
        }
    }
}

Output:

Below we can see the warnings output in the console.

Checking the capacity of HashMap

Explanation of Program:

  • Here we have used a HashMap with initial capacity of 4 and load factor of default (0.75).
  • So HashMap will rehash when the size of HashMap is greater than 4*0.75(3).
  • So, we have input 4 key value pairs.
  • Now, the map is supposed to be resized hence, we have used reflection to check the capacity of the HashMap.
  • The capacity is returned to us as 8.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads