HashSet add: Calling HashMap put
You'll learn exactly how HashSet translates your add() call into the underlying HashMap operation.
The Core Mechanism
When you call add() on a HashSet, the element you're adding becomes the key in the backing HashMap, and the dummy PRESENT object becomes the value. The HashSet then checks the return value from HashMap.put() to determine whether the element was newly added or already existed.
Here's how it works:
public boolean add(E e) {
return map.put(e, PRESENT) == null;
}
This single line does everything:
- Calls
map.put(e, PRESENT)— your element becomes a key, paired with the dummy value - Checks the return value —
HashMap.put()returnsnullif the key didn't exist before, or the old value if it did - Returns true or false —
trueif the element was new (put returnednull),falseif it was already present (put returnedPRESENT)
Why This Works Perfectly
Since all values in the HashMap are the same PRESENT object, the only thing that matters is whether the key was already there. HashMap naturally enforces key uniqueness — exactly what HashSet needs for element uniqueness.
If the element is new, put() returns null → add() returns true.
If the element already exists, put() returns PRESENT → add() returns false.
The HashSet doesn't need any uniqueness logic of its own — it delegates everything to HashMap's key-handling behavior.
Key Takeaway:
HashSet.add(e) directly calls map.put(e, PRESENT) and returns true if the HashMap's put operation returned null, meaning the element was successfully added as a new unique entry.