Java Notes
Complete guide to Java LinkedHashSet — insertion-order preservation, internal working backed by LinkedHashMap, comparison with HashSet and TreeSet, and practical use cases.
What is LinkedHashSet?
java.util.LinkedHashSet is a HashSet with predictable iteration order. It maintains a doubly-linked list across all entries, preserving the insertion order of elements.
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, SerializableThink of it as: HashSet performance + insertion order guarantee.
Characteristics
| Feature | LinkedHashSet |
|---|---|
| Duplicates | Not allowed |
| Ordering | Insertion order preserved |
| Null elements | One null allowed |
| Performance | O(1) for add/remove/contains |
| Backed by | LinkedHashMap |
| Thread-safe | No |
| Memory | More than HashSet (linked list pointers) |
Basic Usage
Set: [Apple, Banana, Cherry, Date] Insertion order preserved! Duplicate Apple added? false Set still: [Apple, Banana, Cherry, Date] After remove Cherry: [Apple, Banana, Date]
Constructors
Time Complexity
| Operation | Average | Worst Case |
|---|---|---|
| ----------- | :-: | :-: |
add(E e) | O(1) | O(log n)* |
remove(Object o) | O(1) | O(log n)* |
contains(Object o) | O(1) | O(log n)* |
size() | O(1) | O(1) |
| Iteration | O(n) | O(n) |
*With treeification (Java 8+)
Iteration Performance: LinkedHashSet vs HashSet
| Set Type | Iteration Time |
|---|---|
| ---------- | :-: |
| HashSet | O(capacity + n) — traverses all buckets including empty |
| LinkedHashSet | O(n) — follows linked list, only visits actual elements |
This means LinkedHashSet iterates faster when the set is sparse (few elements relative to capacity).
Practical Use Cases
1. Remove Duplicates While Preserving Order
This is the #1 use case for LinkedHashSet:
2. Maintaining Display Order
// Menu items should display in the order they were added
Set<String> menuItems = new LinkedHashSet<>();
menuItems.add("Home");
menuItems.add("Products");
menuItems.add("About");
menuItems.add("Contact");
// Always renders: Home → Products → About → Contact
for (String item : menuItems) {
renderMenuItem(item);
}3. Processing Unique Items in Order
// Process each unique URL in the order it was discovered
Set<String> visitedUrls = new LinkedHashSet<>();
visitedUrls.add("https://example.com");
visitedUrls.add("https://example.com/about");
visitedUrls.add("https://example.com"); // Already visited
visitedUrls.add("https://example.com/products");
// Process in discovery order
for (String url : visitedUrls) {
crawl(url);
}4. Ordered Set Operations
LinkedHashSet vs HashSet vs TreeSet
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Ordering | None | Insertion order | Sorted (natural/comparator) |
| add/remove/contains | O(1) | O(1) | O(log n) |
| Iteration | O(capacity) | O(n) | O(n) |
| Backed by | HashMap | LinkedHashMap | TreeMap |
| Null elements | One | One | ❌ None |
| Memory overhead | Lowest | Medium | Highest |
| Use when | Don't care about order | Need insertion order | Need sorted order |
When to Use Which
// Don't care about order — use HashSet (fastest)
Set<String> lookupOnly = new HashSet<>();
// Need insertion order — use LinkedHashSet
Set<String> orderedUnique = new LinkedHashSet<>();
// Need sorted order — use TreeSet
Set<String> sorted = new TreeSet<>();
// Need concurrent access — use ConcurrentHashMap.newKeySet()
Set<String> concurrent = ConcurrentHashMap.newKeySet();Important Behavior Details
Re-insertion Doesn't Change Position
Removal and Re-addition Changes Position
Converting Between Set Types
Thread Safety
// Option 1: Synchronized wrapper
Set<String> syncSet = Collections.synchronizedSet(new LinkedHashSet<>());
// Option 2: Manual synchronization
private final Set<String> set = new LinkedHashSet<>();
private final Object lock = new Object();
public void addItem(String item) {
synchronized (lock) {
set.add(item);
}
}Note: There is no ConcurrentLinkedHashSet in the JDK. For concurrent ordered sets, consider third-party libraries or use ConcurrentHashMap.newKeySet() (which doesn't preserve insertion order).
Common Mistakes
1. Assuming HashSet Preserves Order
// WRONG assumption
Set<String> set = new HashSet<>();
set.add("First");
set.add("Second");
set.add("Third");
// Iteration may NOT be: First, Second, Third!
// CORRECT — use LinkedHashSet for insertion order
Set<String> set = new LinkedHashSet<>();2. Mutating Elements After Adding
// Same problem as HashSet — mutable elements break the set
List<String> item = new ArrayList<>(Arrays.asList("A"));
Set<List<String>> set = new LinkedHashSet<>();
set.add(item);
item.add("B"); // hashCode changes — element is LOST!3. Not Understanding Memory Overhead
// LinkedHashSet uses more memory than HashSet
// Each entry has two extra pointers (before/after)
// For millions of elements, this adds up (~16 bytes per element extra)
// If you don't need order, use HashSet to save memoryPerformance Comparison (Benchmark)
// For 1 million elements:
// Operation | HashSet | LinkedHashSet | TreeSet
// add() | ~120ms | ~150ms | ~800ms
// contains() | ~40ms | ~45ms | ~350ms
// iteration | ~50ms | ~35ms | ~45ms
// memory | ~48MB | ~64MB | ~80MB
// Key insight: LinkedHashSet iterates FASTER than HashSet
// because it doesn't traverse empty bucketsInterview Questions
Q1: How does LinkedHashSet maintain insertion order?
A: It's backed by a LinkedHashMap (not HashMap). LinkedHashMap maintains a doubly-linked list threading through all entries, preserving insertion order.
Q2: What is the difference between LinkedHashSet and HashSet?
A: LinkedHashSet maintains insertion order (predictable iteration). HashSet has no ordering guarantee. LinkedHashSet uses slightly more memory for the linked list pointers.
Q3: Does adding a duplicate element change its position in LinkedHashSet?
A: No. If the element already exists, add() returns false and the element's position in the iteration order remains unchanged.
Q4: What is the time complexity of LinkedHashSet operations?
A: Same as HashSet — O(1) average for add, remove, contains. Iteration is O(n), which is actually better than HashSet's O(capacity + n).
Q5: When should you use LinkedHashSet over HashSet?
A: When you need: (1) unique elements, (2) O(1) operations, AND (3) predictable insertion-order iteration. If you don't need order, HashSet saves memory.
Q6: Can LinkedHashSet maintain access order like LinkedHashMap?
A: No. LinkedHashSet only supports insertion order. Access order (reordering on reads) is only available in LinkedHashMap directly.
Q8: How does LinkedHashSet maintain insertion order?
A: LinkedHashSet extends HashSet but uses a LinkedHashMap internally (instead of HashMap). LinkedHashMap maintains a doubly-linked list threading through all entries in insertion order. During iteration, this linked list is traversed, giving predictable insertion-order iteration.
Q9: What is the performance difference between HashSet and LinkedHashSet?
A: Near-identical for add/remove/contains — both O(1). LinkedHashSet has slightly higher memory overhead (two extra pointers per entry for the linked list) and marginally slower add/remove (maintaining linked list). However, iteration is faster: O(n) for LinkedHashSet vs O(capacity) for HashSet.
Q10: When should you use LinkedHashSet over HashSet?
A: When insertion order matters for iteration, when you need predictable iteration order in tests, when implementing ordered unique collections (like maintaining the order of user actions), or when building ordered result sets that need deduplication while preserving first-occurrence order.
Q11: Does LinkedHashSet support access-order like LinkedHashMap?
A: No. LinkedHashSet always maintains insertion-order only. There's no constructor flag to enable access-order. If you need access-order set behavior, you'd need to build a custom implementation using LinkedHashMap with access-order enabled.
Q12: How do you convert a List to a LinkedHashSet and back while preserving order?
A: List → LinkedHashSet: new LinkedHashSet<>(list) — removes duplicates while preserving first-occurrence order. LinkedHashSet → List: new ArrayList<>(linkedHashSet) — the list will have elements in the set's iteration (insertion) order, with duplicates removed.
Summary
| Aspect | LinkedHashSet |
|---|---|
| Backed by | LinkedHashMap |
| Order | Insertion order |
| Performance | O(1) — same as HashSet |
| Extra cost | ~16 bytes per element for linked list |
| Null | One null allowed |
| Primary use | Remove duplicates preserving order |
| Thread-safe | No |
| When to choose | Need Set + order; don't need sorting |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for LinkedHashSet in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, collections, framework, set
Related Java Master Course Topics