Set Collections
HashSet, LinkedHashSet, TreeSet internals — hashing, ordering, and iteration
- Understand how HashSet achieves O(1) add/contains via HashMap
- Compare HashSet vs LinkedHashSet vs TreeSet ordering guarantees
- Use Set for deduplication problems in production code
Series Context:
This guide is part of a Java Collections series. It assumes familiarity with HashMap, LinkedHashMap, and TreeMap. If you haven't studied those, read those notes first — Set implementations are built directly on top of their Map counterparts.
Table of Contents
- Overview
- Why Set Exists
- Set Interface — Core Characteristics
- Set Hierarchy
- HashSet — Deep Dive
- Set Interface Methods
- Mathematical Set Operations
- LinkedHashSet — Deep Dive
- TreeSet — Deep Dive
- Thread Safety
- ConcurrentModificationException
- Time Complexity Summary
- Comparison Table
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary
1. Overview
The Set interface is part of the Java Collections Framework (java.util package). It models the mathematical concept of a set — an unordered collection with no duplicate elements.
Set is a child interface of Collection, which itself extends Iterable. This means Set inherits all methods from Collection and also adds a few set-specific methods.
1Iterable2 └── Collection3 └── Set4 ├── HashSet5 ├── LinkedHashSet6 └── SortedSet7 └── NavigableSet8 └── TreeSet2. Why Set Exists
Problem: List allows duplicate values. In many real-world scenarios you want a collection of unique items — unique user IDs, unique product codes, unique tags on a blog post. Maintaining uniqueness in a List requires manual contains() checks before every insertion, which is O(n) per operation.
Solution: Set enforces uniqueness automatically and efficiently using hashing (HashSet) or tree-based ordering (TreeSet), giving O(1) or O(log n) uniqueness checks respectively.
Key use cases:
- Removing duplicates from a stream of data
- Membership testing ("is this item already registered?")
- Set-algebra operations: union, intersection, difference
- Storing unique identifiers
3. Set Interface Core Characteristics
| Property | Details |
|---|---|
| Duplicate values | Not allowed |
| Null values | At most one null (depends on implementation) |
| Ordering | Not guaranteed (unless LinkedHashSet or TreeSet) |
| Index access | Not supported |
| Parent interface | Collection |
Set cannot be accessed via index. There is no set.get(0). You must iterate over it using an enhanced for-loop, iterator, or stream.4. Set Hierarchy
5. HashSet Deep Dive
5.1 Overview
HashSet is the most commonly used Set implementation. It stores elements using a hash table internally.
5.2 Internal Working How HashSet Uses HashMap Internally
This is the most important concept to understand about HashSet.
Every HashSet internally contains a HashMap.
When you do:
1Set<Integer> set = new HashSet<>();2set.add(12);Internally, HashSet does:
1map.put(12, PRESENT);Where PRESENT is a private static final dummy Object:
1private static final Object PRESENT = new Object();So the element you insert becomes the key, and the value is always a meaningless dummy object (new Object()).
This is exactly why HashSet cannot have duplicate values — a HashMap cannot have duplicate keys. If you try to add() a value that is already in the set, the put() call finds the key already exists and simply returns, adding nothing.
From the actual JDK source of HashSet.add():
1public boolean add(E e) {2 return map.put(e, PRESENT) == null;3}- Returns
trueif the element was added (key was new). - Returns
falseif the element already existed (key was already present, soputreturned the old valuePRESENT, notnull).
5.3 Why HashSet Does Not Guarantee Order
Because it delegates to HashMap, and HashMap does not guarantee ordering. Elements are stored in buckets based on their hashCode(). The iteration order depends on the hash values, not insertion sequence.
5.4 Null Handling in HashSet
HashSet allows exactly one null element, because HashMap allows one null key.
1Set<String> set = new HashSet<>();2set.add(null); // allowed3set.add(null); // duplicate, silently ignored4System.out.println(set.size()); // 15.5 Basic Code Example
1import java.util.HashSet;2import java.util.Set;3
4public class HashSetDemo {5 public static void main(String[] args) {6 Set<Integer> set = new HashSet<>();7
8 set.add(12);9 set.add(11);10 set.add(33);11 set.add(4);12 set.add(12); // duplicate — ignored13
14 System.out.println(set); // order NOT guaranteed15 System.out.println(set.size()); // 416
17 boolean added = set.add(12);18 System.out.println("Was 12 added again? " + added); // false19 }20}[33, 4, 11, 12] 4 Was 12 added again? false
[33, 4, 11, 12] is not the insertion order. It's the bucket order decided by hashCode(). Do not rely on this.6. Set Interface Methods
Set extends Collection, so it inherits all Collection methods. Below are the key methods:
| Method | Description |
|---|---|
add(E e) | Adds element if not already present. Returns true if added, false if duplicate. |
remove(Object o) | Removes the specified element. Returns true if it was present. |
contains(Object o) | Returns true if the set contains the element. |
size() | Returns the number of elements. |
isEmpty() | Returns true if the set has no elements. |
clear() | Removes all elements. |
iterator() | Returns an Iterator over the elements. |
addAll(Collection c) | Union — adds all elements from another collection (ignores duplicates). |
removeAll(Collection c) | Difference — removes all elements that are also in the given collection. |
retainAll(Collection c) | Intersection — keeps only elements that are also in the given collection. |
containsAll(Collection c) | Returns true if this set contains all elements of the given collection (subset check). |
toArray() | Returns an array containing all elements. |
7. Mathematical Set Operations
Set in Java directly mirrors mathematical set theory. Three core set operations are supported:
7.1 Union `addAll()`
Union = all unique elements from both sets.
1Set 1: {12, 11, 33, 4}2Set 2: {11, 9, 8, 10, 5, 12}3Union: {12, 11, 33, 4, 9, 8, 10, 5}1Set<Integer> set1 = new HashSet<>(Arrays.asList(12, 11, 33, 4));2Set<Integer> set2 = new HashSet<>(Arrays.asList(11, 9, 8, 10, 5, 12));3
4Set<Integer> union = new HashSet<>(set1);5union.addAll(set2);6
7System.out.println("Union: " + union);8// Union: [33, 4, 5, 8, 9, 10, 11, 12] (order may vary)How it works internally: addAll() calls add() for each element in set2. Since add() delegates to map.put(), duplicate keys are silently ignored.
7.2 Intersection `retainAll()`
Intersection = elements common to both sets.
1Set 1: {12, 11, 33, 4}2Set 2: {11, 9, 8, 10, 5, 12}3Intersection: {11, 12}1Set<Integer> set1 = new HashSet<>(Arrays.asList(12, 11, 33, 4));2Set<Integer> set2 = new HashSet<>(Arrays.asList(11, 9, 8, 10, 5, 12));3
4Set<Integer> intersection = new HashSet<>(set1);5intersection.retainAll(set2);6
7System.out.println("Intersection: " + intersection);8// Intersection: [11, 12]7.3 Difference `removeAll()`
Difference = elements in Set 1 that are not in Set 2.
1Set 1: {12, 11, 33, 4}2Set 2: {11, 9, 8, 10, 5, 12}3Difference (Set1 - Set2): {33, 4}1Set<Integer> set1 = new HashSet<>(Arrays.asList(12, 11, 33, 4));2Set<Integer> set2 = new HashSet<>(Arrays.asList(11, 9, 8, 10, 5, 12));3
4Set<Integer> difference = new HashSet<>(set1);5difference.removeAll(set2);6
7System.out.println("Difference: " + difference);8// Difference: [33, 4]7.4 Complete Example
1import java.util.*;2
3public class SetOperationsDemo {4 public static void main(String[] args) {5 Set<Integer> set1 = new HashSet<>(Arrays.asList(12, 11, 33, 4));6 Set<Integer> set2 = new HashSet<>(Arrays.asList(11, 9, 8, 10, 5, 12));7
8 // Union9 Set<Integer> union = new HashSet<>(set1);10 union.addAll(set2);11 System.out.println("Union: " + union);12
13 // Intersection14 Set<Integer> intersection = new HashSet<>(set1);15 intersection.retainAll(set2);16 System.out.println("Intersection: " + intersection);17
18 // Difference (set1 - set2)19 Set<Integer> difference = new HashSet<>(set1);20 difference.removeAll(set2);21 System.out.println("Difference: " + difference);22 }23}Union: [33, 4, 5, 8, 9, 10, 11, 12] Intersection: [11, 12] Difference: [33, 4]
8. LinkedHashSet Deep Dive
8.1 Overview
LinkedHashSet extends HashSet but maintains insertion order. It is backed by a LinkedHashMap internally.
8.2 Internal Working
LinkedHashSet calls the package-private HashSet constructor that accepts a LinkedHashMap:
1HashSet(int initialCapacity, float loadFactor, boolean dummy) {2 map = new LinkedHashMap<>(initialCapacity, loadFactor);3}LinkedHashMap maintains a doubly linked list running through all its entries. This linked list records insertion order. When you iterate over a LinkedHashSet, you traverse this linked list, so elements come out in insertion order.
8.3 Why Access Order Is NOT Supported in LinkedHashSet
LinkedHashMap supports two modes:
- Insertion order (default,
accessOrder = false) - Access order (LRU-style,
accessOrder = true)
When LinkedHashSet creates its internal LinkedHashMap, it never passes accessOrder = true. The constructor always uses false. Even if you pass true internally, LinkedHashSet ignores it. So LinkedHashSet only maintains insertion order, never access order.
8.4 Code Example
1import java.util.LinkedHashSet;2import java.util.Set;3
4public class LinkedHashSetDemo {5 public static void main(String[] args) {6 Set<Integer> set = new LinkedHashSet<>();7
8 set.add(27);9 set.add(7);10 set.add(82);11 set.add(63);12 set.add(5);13 set.add(27); // duplicate — ignored14
15 System.out.println(set); // insertion order guaranteed16 }17}[27, 7, 82, 63, 5]
HashSet.8.5 Thread Safety
LinkedHashSet is not thread-safe, because LinkedHashMap is not thread-safe.
To make it thread-safe:
1Set<Integer> syncSet = Collections.synchronizedSet(new LinkedHashSet<>());9. TreeSet Deep Dive
9.1 Overview
TreeSet implements the NavigableSet interface and stores elements in sorted order (natural ordering by default, or by a custom Comparator). It is backed by a TreeMap internally.
9.2 Internal Working
From the JDK source:
1public TreeSet() {2 this(new TreeMap<>());3}TreeMap uses a Red-Black Tree (a self-balancing binary search tree). All operations (add, remove, contains) are O(log n) because of the tree traversal.
Elements in TreeSet are always stored in sorted order because TreeMap stores keys in sorted order.
9.3 Natural Ordering (Default)
1import java.util.Set;2import java.util.TreeSet;3
4public class TreeSetAscending {5 public static void main(String[] args) {6 Set<Integer> treeSet = new TreeSet<>();7
8 treeSet.add(2);9 treeSet.add(5);10 treeSet.add(63);11 treeSet.add(77);12 treeSet.add(82);13
14 System.out.println(treeSet); // ascending order15 }16}[2, 5, 63, 77, 82]
Elements are sorted in natural ascending order for Integer (Comparable natural ordering).
9.4 Custom Ordering with Comparator
1import java.util.Comparator;2import java.util.Set;3import java.util.TreeSet;4
5public class TreeSetDescending {6 public static void main(String[] args) {7 // Lambda comparator: b - a gives descending order8 Set<Integer> treeSet = new TreeSet<>((a, b) -> b - a);9
10 treeSet.add(2);11 treeSet.add(5);12 treeSet.add(63);13 treeSet.add(77);14 treeSet.add(82);15
16 System.out.println(treeSet); // descending order17 }18}[82, 77, 63, 5, 2]
9.5 Null Handling in TreeSet
TreeSet does not allow null values, because TreeMap does not allow null keys (it needs to call compareTo() or compare() on the key, which throws a NullPointerException).
1TreeSet<String> set = new TreeSet<>();2set.add(null); // throws NullPointerExceptionnull into a TreeSet throws a NullPointerException. This is different from HashSet, which allows one null.9.6 Thread Safety
TreeSet is not thread-safe, because TreeMap is not thread-safe.
10. Thread Safety
10.1 Why Set Implementations Are Not Thread-Safe
All three Set implementations (HashSet, LinkedHashSet, TreeSet) are not thread-safe because their underlying Map implementations (HashMap, LinkedHashMap, TreeMap) are not thread-safe. Multiple threads performing concurrent read/write operations can lead to data corruption or inconsistent state.
10.2 Thread-Safe Set Options
Option 1: Collections.synchronizedSet() (wraps any Set)
1Set<Integer> syncSet = Collections.synchronizedSet(new HashSet<>());2// or3Set<Integer> syncLinkedSet = Collections.synchronizedSet(new LinkedHashSet<>());This wraps every method in a synchronized block, so only one thread can access the set at a time. Simple but can be a bottleneck under high concurrency.
Option 2: ConcurrentHashMap.newKeySet() (preferred for high concurrency)
1import java.util.concurrent.ConcurrentHashMap;2import java.util.Set;3
4Set<Integer> concurrentSet = ConcurrentHashMap.newKeySet();5concurrentSet.add(1);6concurrentSet.add(2);This creates a Set backed by a ConcurrentHashMap, which supports segment-level locking (much better throughput than fully synchronized wrappers). This is the recommended thread-safe Set in modern Java.
Option 3: CopyOnWriteArraySet (good for read-heavy scenarios)
1import java.util.concurrent.CopyOnWriteArraySet;2
3Set<Integer> cowSet = new CopyOnWriteArraySet<>();Creates a new copy of the internal array on every write. Extremely fast reads (no locking), but slow writes. Ideal when reads vastly outnumber writes.
| Option | Mechanism | Best for |
|---|---|---|
synchronizedSet() | Synchronized wrapper | Simple low-concurrency code |
ConcurrentHashMap.newKeySet() | Segment locking | High-concurrency writes |
CopyOnWriteArraySet | Copy-on-write | Read-heavy, rare writes |
11. ConcurrentModificationException
11.1 What Is It?
If you modify a non-thread-safe collection while iterating over it, Java throws ConcurrentModificationException.
1Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));2
3Iterator<Integer> it = set.iterator();4while (it.hasNext()) {5 Integer val = it.next();6 set.add(8); // MODIFYING while iterating → ConcurrentModificationException!7}Why this happens: HashSet's iterator uses a modCount field. Every structural modification (add/remove) increments modCount. The iterator records the modCount at creation time (expectedModCount). On every next() call, it checks modCount == expectedModCount. If they differ, it throws ConcurrentModificationException.
11.2 Safe Way to Remove During Iteration
Use Iterator.remove():
1Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));2
3Iterator<Integer> it = set.iterator();4while (it.hasNext()) {5 Integer val = it.next();6 if (val == 3) {7 it.remove(); // SAFE — uses the iterator's own remove8 }9}10System.out.println(set); // [1, 2, 4, 5]11.3 Safe Way to Add/Remove in Multi-threaded Scenarios
Use a thread-safe set:
1Set<Integer> concurrentSet = ConcurrentHashMap.newKeySet();2concurrentSet.addAll(Arrays.asList(1, 2, 3, 4, 5));3
4// Thread 1: iterating5for (Integer val : concurrentSet) {6 System.out.println(val);7}8
9// Thread 2: adding (concurrent, no exception)10concurrentSet.add(8);12. Time Complexity Summary
| Operation | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
add(e) | O(1) amortized | O(1) amortized | O(log n) |
remove(e) | O(1) amortized | O(1) amortized | O(log n) |
contains(e) | O(1) amortized | O(1) amortized | O(log n) |
size() | O(1) | O(1) | O(1) |
| Iteration | O(n) | O(n) | O(n) |
addAll() (union) | O(n) | O(n) | O(n log n) |
retainAll() | O(n) | O(n) | O(n log n) |
removeAll() | O(n) | O(n) | O(n log n) |
Why O(1) for HashSet/LinkedHashSet? Because they use hashing. hashCode() maps the element to a bucket in O(1). Assuming a good hash function, collision chains stay short.
Why O(log n) for TreeSet? Because it uses a Red-Black Tree. Every insert/lookup traverses a tree of height O(log n).
13. Comparison Table
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Backed by | HashMap | LinkedHashMap | TreeMap |
| Order | No order guarantee | Insertion order | Sorted (natural/custom) |
| Null allowed | Yes (one null) | Yes (one null) | No |
| Duplicates | No | No | No |
| Thread-safe | No | No | No |
| Time complexity | O(1) amortized | O(1) amortized | O(log n) |
| Use case | Fast lookups, no order needed | Order matters | Sorted iteration needed |
Comparable required | No | No | Yes (or provide Comparator) |
14. Common Mistakes
Mistake 1: Expecting Order from HashSet
1Set<Integer> set = new HashSet<>();2set.add(3);3set.add(1);4set.add(2);5System.out.println(set); // might print [1, 2, 3] — looks ordered, but it's NOT guaranteedHashSet output may appear ordered for small integer sets because Java's integer hash codes are the integers themselves, and buckets happen to line up. Do NOT rely on this. Use LinkedHashSet for insertion order or TreeSet for sorted order.Mistake 2: Adding Null to TreeSet
1TreeSet<String> set = new TreeSet<>();2set.add(null); // NullPointerException!Fix: Use HashSet or LinkedHashSet if null values are possible.
Mistake 3: Modifying Set During Iteration
1for (Integer val : set) {2 set.remove(val); // ConcurrentModificationException3}Fix: Use Iterator.remove() or collect elements to remove separately:
1Set<Integer> toRemove = new HashSet<>();2for (Integer val : set) {3 if (val % 2 == 0) toRemove.add(val);4}5set.removeAll(toRemove);Mistake 4: Accessing Set by Index
1set.get(0); // Compilation error — Set has no get(int index) methodFix: Iterate or convert to List:
1List<Integer> list = new ArrayList<>(set);2list.get(0); // now you can indexMistake 5: Assuming `add()` Throws Exception for Duplicates
1set.add(12);2set.add(12); // NOT an exception — silently returns falseFix: Check the return value if you need to know:
1boolean wasAdded = set.add(12);2if (!wasAdded) System.out.println("12 was already in the set");15. Best Practices
- Choose the right implementation:
- Need fast lookups, don't care about order →
HashSet - Need insertion order preserved →
LinkedHashSet - Need sorted iteration →
TreeSet - Need thread safety →
ConcurrentHashMap.newKeySet()
- Always program to the interface:
1 Set<String> set = new HashSet<>(); // good2 HashSet<String> set = new HashSet<>(); // avoid — limits flexibility- Override
equals()andhashCode()for custom objects:
HashSet's uniqueness guarantee depends on hashCode() and equals(). If your custom class doesn't override them, two logically equal objects may both be added.
1 class Person {2 String name;3 @Override public boolean equals(Object o) { ... }4 @Override public int hashCode() { ... }5 }- Use
addAll(),retainAll(),removeAll()for set algebra instead of manual loops.
- Prefer
ConcurrentHashMap.newKeySet()overCollections.synchronizedSet()for concurrent code.
16. Interview Notes
Commonly Asked Questions
Q1: Why doesn't Set allow duplicate values?
Because internally it uses HashMap. When you call set.add(x), it calls map.put(x, PRESENT). HashMap cannot have duplicate keys. If the key already exists, put() simply overwrites the value (which is the dummy PRESENT object anyway) and returns — so the element count stays the same.
Q2: What data structure does HashSet use internally?
HashMap. The element you insert becomes the key, and the value is a static dummy Object called PRESENT.
Q3: What is the time complexity of HashSet operations?
O(1) amortized for add, remove, contains. Worst case is O(n) if there are many hash collisions (all elements in one bucket), but this is extremely rare with a good hash function.
Q4: How does LinkedHashSet maintain insertion order?
It is backed by LinkedHashMap, which internally maintains a doubly linked list through all entries. This linked list records the insertion sequence. Iteration follows the linked list.
Q5: Why does TreeSet use O(log n) time complexity?
TreeSet is backed by TreeMap, which uses a Red-Black Tree (a self-balancing binary search tree). The height of a Red-Black Tree with n nodes is always O(log n), so all operations that traverse the tree are O(log n).
Q6: Can TreeSet store null values?
No. TreeMap needs to compare keys using compareTo() or compare(). Calling null.compareTo(anything) throws a NullPointerException.
Q7: What is ConcurrentModificationException? When does it occur?
It is thrown when a non-thread-safe collection is structurally modified while being iterated (via an iterator). The iterator uses a modCount mechanism to detect this. Fix: use Iterator.remove() for safe removal during iteration, or use a thread-safe collection.
Q8: How to get a thread-safe Set in Java?
Three options:
Collections.synchronizedSet(new HashSet<>())ConcurrentHashMap.newKeySet()(preferred)CopyOnWriteArraySet
Q9: What is the difference between HashSet, LinkedHashSet, and TreeSet?
See the comparison table above.
Q10: Why does LinkedHashSet not support access order like LinkedHashMap?
When LinkedHashSet creates its internal LinkedHashMap, it never passes accessOrder = true. The API doesn't expose this option, so access order tracking is disabled — only insertion order is maintained.
17. Practice Questions
Easy
- Create a
HashSetofStringand add:"apple","banana","apple","cherry". Print the set and its size.
- Verify that
set.add()returnsfalsewhen adding a duplicate. Write a program to demonstrate this.
- Convert a
Listwith duplicates[1, 2, 2, 3, 3, 3, 4]into aSetto remove duplicates. Print the result.
- Create a
LinkedHashSetand demonstrate that insertion order is preserved.
- Create a
TreeSetand add names. Print them. What order are they in?
Medium
- Given two
Set, write a program to compute:
- Union
- Intersection
- Difference (A - B) and (B - A)
- Write a program that demonstrates
ConcurrentModificationExceptionand then fix it usingIterator.remove().
- Create a
TreeSetwith a customComparatorto sort strings by length (ascending). What happens if two strings have the same length? (Hint: TreeSet uses comparator for equality too.)
- Write a thread-safe
SetusingConcurrentHashMap.newKeySet()and simulate two threads — one adding elements and one iterating — without throwing exceptions.
- Write a method that accepts a
Stringsentence and returns aSetof all unique characters (ignoring spaces).
Hard
- Implement your own simplified
MyHashSetusing aHashMapinternally. Implementadd(),remove(),contains(), andsize().
- Explain why the following can cause a bug with
HashSet:
1 class Box {2 int value;3 Box(int v) { this.value = v; }4 }5 Set<Box> set = new HashSet<>();6 Box b = new Box(5);7 set.add(b);8 b.value = 10;9 System.out.println(set.contains(b)); // what does this print and why?- Design a system where you need to maintain a collection of unique usernames that preserves signup order and is thread-safe. Which
Settype(s) would you use?
18. Summary
Revision Bullets:
Set=Collectionwith no duplicates and no index access.HashSetusesHashMapinternally; element → key, dummyObject→ value.add()returnsfalsefor duplicates (no exception thrown).HashSetdoes not guarantee order.LinkedHashSetpreserves insertion order.TreeSetprovides sorted order.LinkedHashSetuses aLinkedHashMapwith a doubly linked list for ordering.LinkedHashSetonly supports insertion order, not access order.TreeSetusesTreeMap(Red-Black Tree) → O(log n) for all operations.TreeSetdoes not allownull(TreeMap needs to compare keys).- None of the three are thread-safe. Use
ConcurrentHashMap.newKeySet()for thread safety. ConcurrentModificationExceptionis thrown when you structurally modify a collection while iterating it with an iterator.- Set algebra:
addAll= union,retainAll= intersection,removeAll= difference. - Always override
equals()andhashCode()in custom objects used insideHashSetorLinkedHashSet.
Mastery check
How well can you recall this?
Finished this lesson?