Course contentsShow
← Java
Lesson 1049 of 2,87025. Set ImplementationsFree lesson

HashSet add: Calling HashMap put

How adding an element to HashSet translates to putting a key-value pair in the backing HashMap.

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:

  1. Calls map.put(e, PRESENT) — your element becomes a key, paired with the dummy value
  2. Checks the return value — HashMap.put() returns null if the key didn't exist before, or the old value if it did
  3. Returns true or false — true if the element was new (put returned null), false if it was already present (put returned PRESENT)

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.