Threshold: When Rehashing Triggers
What you'll learn: You'll understand the precise calculation that determines when HashSet triggers an expensive rehashing operation.
The Threshold Formula
The threshold is the exact number of elements that, when reached, forces HashSet to rehash. It's calculated simply:
threshold = capacity × load factor
With the default load factor of 0.75 and default initial capacity of 16:
threshold = 16 × 0.75 = 12
This means your HashSet will rehash when you add the 13th element (because size would exceed 12).
How Threshold Works in Practice
Every time you add() an element to HashSet (which uses put() on its backing HashMap), the internal logic checks:
if (size >= threshold) {
// Time to rehash!
// Double the capacity and redistribute all elements
}
The threshold updates after each rehashing. If capacity doubles to 32, the new threshold becomes:
threshold = 32 × 0.75 = 24
Why This Matters
Understanding threshold helps you predict performance. If you know you'll store 100 elements:
- Default capacity (16) requires multiple rehashes
- Pre-sizing to capacity 128 sets threshold to 96, avoiding rehashes entirely
The threshold is the tripwire that guards against the backing array becoming too crowded, maintaining performance by triggering expansion before things degrade.
Key Takeaway: The threshold (capacity × load factor) is the exact size limit that triggers rehashing—once your HashSet's size meets or exceeds this value, all elements get redistributed into a larger array.