Specifying Initial Capacity to Avoid Rehashing
What You'll Learn
You'll learn how to set an appropriate initial capacity when creating a HashMap to minimize or eliminate costly rehashing operations.
The Problem: Rehashing Is Expensive
By now you know that rehashing—triggered when the number of entries exceeds the threshold—requires creating a new larger array, recalculating hash indices, and redistributing all entries. This is a performance bottleneck, especially for large maps.
The good news: If you know approximately how many entries your HashMap will hold, you can avoid most or all rehashing by specifying a proper initial capacity upfront.
Setting Initial Capacity
HashMap provides constructors that accept an initial capacity:
// If you expect around 1000 entries:
HashMap<String, Integer> map = new HashMap<>(1000);
But wait! Remember the load factor (default 0.75). The threshold is capacity × loadFactor. So a capacity of 1000 actually triggers rehashing at 750 entries.
The Formula
To hold n entries without rehashing:
Initial Capacity = (n / loadFactor) + 1
For 1000 entries with load factor 0.75:
// 1000 / 0.75 = 1333.33, round up
HashMap<String, Integer> map = new HashMap<>(1334);
Now your map can accommodate 1000 entries without any rehashing operations.
The Analogy
Think of a moving truck. If you know you have 50 boxes, renting a truck that holds exactly 50 (but starts rehashing at 37) means you'll need a second truck mid-move. Better to rent one that comfortably fits 50 from the start.
Key Takeaway: When you know the expected size of your HashMap, calculate the appropriate initial capacity using expectedSize / loadFactor + 1 to eliminate rehashing overhead and improve performance.