Lesson · Collections Framework
Set: uniqueness, and the map hiding inside
11 min readSet
A Set enforces uniqueness through equals/hashCode, and HashSet pulls it off by being a HashMap in disguise, with the elements as keys. That one fact explains its speed and its one rule: never mutate an element after adding it.
Membership, not position
A Set answers one question well: is this thing in here, or put it in if it isn't. No indices, no positions, no duplicates. The operations are add, remove, contains, and set algebra like addAll (union) and retainAll (intersection).
add returns a boolean that is easy to ignore and occasionally the whole point: true if the element was new, false if an equal element was already present, and in the false case the set keeps the original.
Three flavours, one contract
HashSet stores its elements in a HashMap: the element is the key, and a single shared dummy object is every value. That is the entire implementation. Which means every performance and correctness fact from the HashMap internals lesson applies verbatim: O(1) average add/contains, unordered iteration, equals/hashCode decide identity.
LinkedHashSet additionally threads a linked list through the entries, preserving insertion order at a small memory cost. TreeSet skips hashing entirely and keeps elements sorted via Comparable or a Comparator: O(log n) operations and a bonus contract, NavigableSet, with floor, ceiling, headSet and tailSet for range queries.
One more worth knowing: EnumSet, built on a bit vector, is dramatically fast for enum elements: a bitset in a Set costume.
The map hiding inside
HashSet is not merely like a map, it is one. The elements are keys, every value is the same shared dummy object, and the whole Set interface is a thin translation of the Map interface:
| Set call | What the hidden map does |
|---|---|
add(e) | map.put(e, PRESENT): the set only cares whether the key was new |
contains(e) | map.containsKey(e) |
remove(e) | map.remove(e) |
size() | map.size() |
| iteration | iterates map.keySet() |
- The family mirrors: LinkedHashSet wraps a LinkedHashMap (order), and TreeSet wraps a TreeMap, floor and ceiling included.
- That is why every rule is shared: equals/hashCode decide identity for both structures, a mutable key breaks a map and a mutable element breaks a set, and collisions underneath are the same bucket chains from the HashMap lesson.
One machine, two outfits. Uniqueness is exactly what map keys give, so the JDK built the machine once and dressed it twice.
Bridge board · one machine, two outfits
click a Set call, watch the Map callHashSet · what you use
HashMap · what runs
PRESENT is a single shared object: the set only ever asks which keys exist, never what they hold.
Delegation log
set = new HashSet<>() → map = new HashMap<>() behind it
The family mirrors: LinkedHashSet wraps LinkedHashMap, and TreeSet wraps TreeMap, floor and ceiling included.
Uniqueness is only as good as equals
A HashSet is a promise enforced by two methods you write. Forget hashCode and equal objects land in different buckets, so the set happily keeps both "duplicates". Override hashCode without equals, or mutate a field after adding the element, and contains() starts lying.
Records, enums and the IDE's auto-generated pair get this right for free. A hand-written class used as a set element or map key should be immutable in the fields that participate: mutate one and the element becomes unreachable, still occupying a slot you can never find.
Idioms and edges
The classic one-liner: new HashSet<>(list): instant dedup, original order lost. new LinkedHashSet<>(list) dedups while keeping first-seen order, which is what you usually meant.
Set.of(...) is immutable and throws on duplicates at construction: a useful assertion when building from constants. Set.of's runtime is HashSet's; do not confuse the two.
For threads, reach for ConcurrentHashMap.newKeySet(), a Set view that is genuinely concurrent, rather than Collections.synchronizedSet, which serialises every call. And remember iteration order: HashSet guarantees nothing, so never let UI or tests depend on it.
A Set cannot hold two equal elements, but it can hold one unreachable one
Mutate a field that equals/hashCode depends on after add(), and the element's hash changes: contains() hashes to the new bucket and misses the old slot, so the set 'loses' the element while it still sits inside. Same disease as mutable map keys, same cure: treat set elements as immutable.
Interview angles
How does HashSet actually work internally?+
It wraps a HashMap: add(e) is map.put(e, PRESENT) for a shared dummy value object. equals/hashCode select the bucket and match the key, giving O(1) average add/contains, with the same resize behaviour as HashMap.
What does add() return, and what happens on a duplicate?+
true if the element was inserted, false if an equal element already existed. On the duplicate path the existing element is kept and the new one discarded, a detail that matters when the two are equal by equals but differ in other fields.
HashSet vs LinkedHashSet vs TreeSet: pick one for each use.+
HashSet: default, fastest, unordered. LinkedHashSet: when iteration must follow insertion (predictable output, caches keyed by first appearance). TreeSet: when you need sorted iteration or range operations (floor, ceiling, headSet) at O(log n).
When does a HashSet break?+
Three ways: equals without hashCode (duplicates survive), mutating an element used in the pair (element becomes unreachable), and sharing it between threads without synchronisation (loss or corruption). All three are contracts, not bugs.