Why this matters
- A
Setis the clearest way to express "membership matters, duplicates do not", and using aListwithcontainsinstead is a common and avoidable O(n) mistake. - Which set you pick determines whether iteration order is arbitrary, insertion-based or sorted, and that silently affects test reliability.
- Uniqueness depends entirely on
equalsandhashCode, so a broken contract shows up here first.
Three implementations
| Aspect | Implementation | Properties |
|---|---|---|
| HashSet | No order guarantee | O(1) add, remove, contains |
| LinkedHashSet | Insertion order preserved | O(1), slightly more memory for the links |
| TreeSet | Sorted order | O(log n), plus navigation and range queries |
HashSet
ImplementationNo order guaranteePropertiesO(1) add, remove, containsLinkedHashSet
ImplementationInsertion order preservedPropertiesO(1), slightly more memory for the linksTreeSet
ImplementationSorted orderPropertiesO(log n), plus navigation and range queries
Each wraps a map internally: HashSet over HashMap, LinkedHashSet over LinkedHashMap, TreeSet over TreeMap.
Each dropped the duplicate "ana". Only the ordering differs.
Uniqueness depends on your contract
A HashSet decides whether an element is already present by hashing it and then comparing with
equals. A broken contract breaks the set.
TreeSet uses compareTo or a supplied Comparator instead, so it has the same dependency on a
different method. Two elements comparing as 0 are considered duplicates even if equals disagrees.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- TreeSet navigation
- Set algebra
- EnumSet for enum keys
- Choosing
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.