HashSet size and isEmpty: Direct Delegation
You'll learn how HashSet implements its size() and isEmpty() methods by simply forwarding the call to the underlying HashMap.
The Simplest Methods
Since HashSet is built on top of HashMap, retrieving basic state information is straightforward. The size() and isEmpty() methods don't need any special logic—they just ask the backing HashMap for the answer.
How It Works
When you call size() on a HashSet, it directly delegates to the HashMap's size() method, which returns the number of key-value pairs. Since each element in the HashSet corresponds to exactly one key in the HashMap (with that dummy PRESENT value), the counts match perfectly.
Similarly, isEmpty() checks whether the backing HashMap has zero entries. If the map is empty, the set is empty.
The Implementation
public int size() {
return map.size(); // Direct delegation to HashMap
}
public boolean isEmpty() {
return map.isEmpty(); // Direct delegation to HashMap
}
Why This Works Perfectly
Think of it like checking how many books are on a shelf. The HashSet doesn't need to count anything itself—it already has a librarian (HashMap) who knows exactly how many items are stored. Why duplicate that work when you can just ask?
Both operations run in O(1) constant time because HashMap maintains an internal counter that's updated during insertions and removals.
Key Takeaway: HashSet's size() and isEmpty() methods are trivial wrappers that delegate directly to the underlying HashMap, leveraging its internal size tracking without any additional overhead.