Custom Initial Capacity and Load Factor
What you'll learn: How to use HashSet constructors to specify initial capacity and load factor for performance tuning.
Now that you understand how load factor and rehashing work internally, you can take control of these parameters when creating a HashSet.
The Specialized Constructors
HashSet provides constructors that let you customize its performance characteristics:
// Default: capacity 16, load factor 0.75
HashSet<String> set1 = new HashSet<>();
// Custom initial capacity only (load factor still 0.75)
HashSet<String> set2 = new HashSet<>(100);
// Custom capacity AND load factor
HashSet<String> set3 = new HashSet<>(100, 0.9f);
When to Use Custom Values
Custom initial capacity helps when you know roughly how many elements you'll store. If you're adding 1000 elements, starting with capacity 1000 avoids multiple expensive rehashing operations.
Custom load factor is a space-time trade-off:
- Higher load factor (like 0.9): Saves memory by keeping the table denser, but increases collision likelihood and lookup time
- Lower load factor (like 0.5): Uses more memory but reduces collisions for faster operations
Practical Example
// You know you'll store about 10,000 unique user IDs
// Calculate capacity: 10,000 / 0.75 ≈ 13,334
HashSet<Integer> userIds = new HashSet<>(13334);
// Memory-constrained environment: pack tighter
HashSet<String> cache = new HashSet<>(50, 0.9f);
Think of it like reserving a parking lot: if you know 100 cars are coming, build 133 spaces (with default 0.75 factor) to avoid expanding the lot mid-event.
Key Takeaway: Use the HashSet constructors with custom initial capacity (and optionally load factor) to prevent rehashing overhead when you know the expected size, or to tune the memory-speed balance for specific use cases.