Capacity vs Size in HashSet
You'll learn how HashSet's capacity and size represent two different measures that beginners often confuse.
The Core Distinction
When working with a HashSet, two numbers matter:
- Size: The actual number of elements currently stored in the set
- Capacity: The number of buckets in the underlying hash table (the internal array length)
These are not the same thing. The capacity is always greater than or equal to the size, and it determines how much space is available before the hash table needs to resize.
Why Both Matter
Think of a HashSet like a parking garage:
- Capacity is the total number of parking spaces available (even empty ones)
- Size is the number of cars actually parked right now
When you call add(), the size increases by one if the element is new. But the capacity only changes when the hash table resizes—which happens when the size exceeds capacity × loadFactor.
Accessing These Values
HashSet<String> set = new HashSet<>(16); // capacity = 16
set.add("apple"); // size = 1, capacity still 16
set.add("banana"); // size = 2, capacity still 16
int currentSize = set.size(); // returns 2
// Note: no public method to check capacity directly!
The size() method tells you how many elements are stored. However, HashSet doesn't expose a method to check the current capacity—it's an internal implementation detail managed automatically.
Key Takeaway: Size counts the elements you've added; capacity determines the internal storage space before resizing. Size is what you care about as a user; capacity is what the HashSet manages behind the scenes for performance.