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

HashSet as a HashMap Wrapper

Understanding that HashSet is implemented internally using a HashMap with dummy values.

HashSet as a HashMap Wrapper

You'll learn how Java's HashSet cleverly reuses HashMap internally by storing dummy values.

The Surprising Implementation Truth

When you use a HashSet, you might think it's a completely separate data structure optimized for storing unique elements. But here's the secret: HashSet is actually just a thin wrapper around HashMap. Instead of reinventing the wheel, Java's designers reused the already-efficient hashing mechanism of HashMap.

How the Wrapper Works

In a HashMap, you store key-value pairs. But a HashSet only needs to store elements (no values). The solution? HashSet uses your elements as keys in an internal HashMap and pairs each one with a dummy value — typically just a constant Object instance.

When you call add(element) on a HashSet, internally it calls put(element, PRESENT) on its private HashMap, where PRESENT is just a placeholder object. The dummy value serves no purpose except to satisfy the HashMap API requirement.

The Analogy

Imagine a coat check where you're only interested in tracking which coat numbers are in use. Instead of building a new system, you use your existing key-value filing cabinet — you file each coat number (the key) with a sticky note that just says "YES" (the dummy value). You never look at the sticky notes; you only care whether the folder exists.

Why This Design?

This approach avoids code duplication. HashMap already handles hashing, collision resolution, resizing, and all the complexity. HashSet gets all these features "for free" by delegating to HashMap.

Key Takeaway: HashSet is implemented as a HashMap where your elements become keys and all values are the same dummy constant — a brilliant example of code reuse through composition.