Initial Capacity and Load Factor in HashSet
You'll learn: How HashSet's constructors pass capacity and load factor parameters directly to the backing HashMap that actually stores the data.
The Delegation Pattern
Remember that HashSet is essentially a thin wrapper around HashMap. When you create a HashSet, you're really creating a HashMap behind the scenes. The constructors in HashSet accept two important parameters—initial capacity and load factor—and immediately forward them to the HashMap constructor.
Initial Capacity
The initial capacity determines how many "buckets" the internal hash table starts with. Just like specifying initial capacity in ArrayList prevents resizing overhead, choosing the right initial capacity for HashSet (and its backing HashMap) avoids expensive rehashing operations as elements are added.
// Default: capacity 16, load factor 0.75
HashSet<String> set1 = new HashSet<>();
// Specify initial capacity
HashSet<String> set2 = new HashSet<>(100);
// Specify both capacity and load factor
HashSet<String> set3 = new HashSet<>(100, 0.5f);
Load Factor
The load factor is a threshold (typically 0.75) that determines when the hash table should resize. When the number of elements exceeds capacity × loadFactor, the backing HashMap automatically grows and rehashes all entries.
Think of it like this: If you have 16 buckets and a 0.75 load factor, the table will resize when you add the 13th element (16 × 0.75 = 12).
A lower load factor means more empty space but faster lookups. A higher load factor saves memory but risks slower performance due to more collisions.
Key Takeaway: HashSet constructors simply pass capacity and load factor arguments straight through to the backing HashMap, allowing you to tune performance and memory usage for your specific workload.