Difference Between HashSet and LinkedHashSet in Java
HashSet and LinkedHashSet are both hash-based Set implementations: they store unique elements, allow one null, and offer O(1) average add, remove and contains. The difference is iteration order:
HashSetmakes no ordering guarantee; elements come out in an order determined by their hash codes, which may change as the set grows.LinkedHashSet(a subclass ofHashSet) also keeps a doubly linked list through its entries, so iteration follows insertion order.
1. Comparison Table
| Aspect | HashSet | LinkedHashSet |
|---|---|---|
| Iteration order | Unpredictable | Insertion order |
| Internal structure | Backed by HashMap | Backed by LinkedHashMap (hash table + linked list) |
| Hierarchy | Implements Set | Extends HashSet; implements SequencedSet (Java 21) |
| add / remove / contains | O(1) average | O(1) average, slightly slower |
| Iteration cost | Proportional to capacity + size | Proportional to size only |
| Memory | Lower | Higher (two extra references per entry) |
| Null | One null | One null |
| Since | Java 1.2 | Java 1.4 |
2. Order in Action
import java.util.*;
public class OrderDemo {
public static void main(String[] args) {
List<String> visits = List.of("Pune", "Delhi", "Kochi", "Agra", "Delhi", "Mumbai", "Pune");
Set<String> hash = new HashSet<>(visits);
Set<String> linked = new LinkedHashSet<>(visits);
System.out.println("input : " + visits);
System.out.println("HashSet : " + hash + " <- order depends on hash codes");
System.out.println("LinkedHashSet : " + linked + " <- insertion order kept");
linked.remove("Delhi");
linked.add("Delhi"); // re-adding moves it to the end
linked.add("Kochi"); // already present: position unchanged
System.out.println("after remove + re-add Delhi: " + linked);
// Java 21: SequencedSet methods on LinkedHashSet
LinkedHashSet<String> seq = new LinkedHashSet<>(linked);
System.out.println("getFirst/getLast: " + seq.getFirst() + " / " + seq.getLast());
seq.addFirst("Goa");
System.out.println("addFirst(Goa) : " + seq + ", reversed: " + seq.reversed());
}
}
input : [Pune, Delhi, Kochi, Agra, Delhi, Mumbai, Pune] HashSet : [Delhi, Kochi, Pune, Agra, Mumbai] <- order depends on hash codes LinkedHashSet : [Pune, Delhi, Kochi, Agra, Mumbai] <- insertion order kept after remove + re-add Delhi: [Pune, Kochi, Agra, Mumbai, Delhi] getFirst/getLast: Pune / Delhi addFirst(Goa) : [Goa, Pune, Kochi, Agra, Mumbai, Delhi], reversed: [Delhi, Mumbai, Agra, Kochi, Pune, Goa]
- Duplicates are removed by both; only
LinkedHashSetkeeps the first-seen order. - Re-inserting an existing element does not change its position; removing and adding it again moves it to the end.
- Since Java 21,
LinkedHashSetis aSequencedSetwithgetFirst,getLast,addFirst,addLastandreversed.
3. Performance
import java.util.*;
public class PerfDemo {
static long ms(Runnable r) { long s = System.nanoTime(); r.run(); return (System.nanoTime() - s) / 1_000_000; }
public static void main(String[] args) {
int n = 1_000_000;
Set<Integer> hash = new HashSet<>(), linked = new LinkedHashSet<>();
long hAdd = ms(() -> { for (int i = 0; i < n; i++) hash.add(i); });
long lAdd = ms(() -> { for (int i = 0; i < n; i++) linked.add(i); });
long hIter = ms(() -> { long s = 0; for (int x : hash) s += x; });
long lIter = ms(() -> { long s = 0; for (int x : linked) s += x; });
System.out.printf("add 1M : HashSet %4d ms | LinkedHashSet %4d ms%n", hAdd, lAdd);
System.out.printf("iterate 1M: HashSet %4d ms | LinkedHashSet %4d ms%n", hIter, lIter);
}
}
add 1M : HashSet 32 ms | LinkedHashSet 37 ms iterate 1M: HashSet 9 ms | LinkedHashSet 5 ms
Adding is marginally slower for LinkedHashSet because it maintains links, while iteration can be faster because it follows the list instead of scanning empty buckets. The differences are small; choose based on whether you need ordering.
4. When to Use Which
HashSet: you only need uniqueness and fast membership tests, and order is irrelevant. It is the default choice.LinkedHashSet: you need uniqueness and a predictable order, for example removing duplicates from a list while preserving order, or displaying unique items as they were entered.TreeSet: you need elements sorted rather than in insertion order. See LinkedHashSet vs TreeSet.
5. Summary
- Both store unique elements with O(1) average operations and allow one null.
HashSethas no defined order;LinkedHashSetkeeps insertion order.LinkedHashSetuses a bit more memory and adds Java 21 sequenced methods.- Neither is thread-safe.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is the main difference between HashSet and LinkedHashSet?
LinkedHashSet maintains insertion order; HashSet does not guarantee any order.
Q2. Is LinkedHashSet a subclass of HashSet?
Yes. It extends HashSet and uses a LinkedHashMap internally.
Q3. Which is faster?
HashSet is slightly faster for adding and removing; LinkedHashSet can iterate faster. The differences are small.
Q4. Which uses more memory?
LinkedHashSet, because each entry stores two extra references for the linked list.
Q5. Does LinkedHashSet allow duplicates?
No. Like every Set, it stores unique elements.
Q6. Do both allow null?
Yes, one null element each.
Q7. Does re-adding an element change its position?
No. Insertion order is not affected when an element is re-inserted; remove it first to move it to the end.
Q8. Is HashSet order random?
It is not random but depends on hash codes and capacity, so it can change as the set grows. Never rely on it.
Q9. Are they thread-safe?
No. Use Collections.synchronizedSet or ConcurrentHashMap.newKeySet().
Q10. How do I remove duplicates from a list but keep order?
new ArrayList<>(new LinkedHashSet<>(list)).
Q11. What is SequencedSet?
A Java 21 interface for sets with a defined encounter order, providing first/last access and a reversed view. LinkedHashSet and TreeSet implement it.
Q12. Can LinkedHashSet be ordered by access?
No. Access order is a feature of LinkedHashMap only.
Q13. Are their iterators fail-fast?
Yes. Modifying the set during iteration (other than via the iterator) throws ConcurrentModificationException.
Q14. What are the default capacity and load factor?
16 and 0.75 for both.
Q15. Do both need equals and hashCode?
Yes. Both use the element's hashCode and equals to detect duplicates.
Q16. How do I convert a HashSet to a LinkedHashSet?
new LinkedHashSet<>(hashSet); the order will be the HashSet's iteration order at that moment.
Q17. Which should I use for unique, sorted data?
Neither: use TreeSet.
Q18. Does LinkedHashSet support index access?
No. Sets have no indexes, although Java 21 adds first and last element access.
Q19. Is the time complexity the same?
Yes, O(1) average for add, remove and contains in both.
Q20. What does Set.of return?
An immutable set with unspecified iteration order, more like a HashSet than a LinkedHashSet.