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

HashSet remove: HashMap remove Operation

How removing from HashSet calls remove on the backing HashMap and returns success status.

HashSet remove: HashMap remove Operation

You'll learn how HashSet's remove() method delegates to the backing HashMap and returns whether an element was actually removed.

Core Concept

Just as add() and contains() delegate to the underlying HashMap, HashSet's remove() method is a thin wrapper around HashMap.remove(). When you remove an element from a HashSet, you're actually removing a key from the backing map. The method returns true if the element existed (and was removed), or false if it wasn't there to begin with.

How It Works

When you call remove() on a HashSet, here's what happens internally:

public boolean remove(Object o) {
    return map.remove(o) == PRESENT;
}

The HashSet asks its backing HashMap to remove the key. Remember, every element in the set is stored as a key in the map with that dummy PRESENT value. The HashMap.remove() method returns the value that was associated with the key—or null if the key wasn't found.

By checking if the returned value equals PRESENT, the HashSet can tell whether the element actually existed. If it did, remove() returns true (success). If not, it returns false.

Example in Action

HashSet<String> names = new HashSet<>();
names.add("Alice");

boolean removed1 = names.remove("Alice");  // true - was present
boolean removed2 = names.remove("Bob");    // false - not in set

Behind the scenes, the first remove() finds "Alice" as a key in the map, removes it, gets back PRESENT, and returns true. The second finds no "Bob" key, gets back null, and returns false.

Key Takeaway:
HashSet.remove() delegates to HashMap.remove() and returns true only if the element was actually present (detected by checking if the removed value equals PRESENT).