🌟 Let’s compare LinkedHashSet
vs HashSet
, since they’re closely related — but behave differently in one key way.
🔍 ✅ Quick Answer:
LinkedHashSet
is just likeHashSet
, but it maintains insertion order of the elements.
🔑 Core Differences
Feature | HashSet | LinkedHashSet |
---|---|---|
Order of elements | ❌ Unpredictable (hash-based order) | ✅ Preserves insertion order |
Performance | ⚡ Very fast (O(1) typical) | ⚡ Slightly slower (extra overhead) |
Under the hood | Backed by HashMap<K, Object> | Backed by LinkedHashMap<K, Object> |
Memory usage | 🔹 Lower | 🔺 Slightly higher (stores ordering) |
🔧 Example:
Set<String> hashSet = new HashSet<>();
hashSet.add("banana");
hashSet.add("apple");
hashSet.add("cherry");
System.out.println(hashSet);
// Output could be: [apple, cherry, banana] (no guarantee)
Set<String> linkedSet = new LinkedHashSet<>();
linkedSet.add("banana");
linkedSet.add("apple");
linkedSet.add("cherry");
System.out.println(linkedSet);
// Output: [banana, apple, cherry] ✅ (insertion order)
🧠 How LinkedHashSet
works internally
- It inherits from
HashSet
. - It uses a
LinkedHashMap
internally, which:- Has a doubly linked list connecting entries in insertion order.
- This is what preserves order during iteration.
🚀 Use Case Summary:
Use Case | Recommended Set |
---|---|
Don’t care about order (best speed) | HashSet |
Need predictable iteration order | LinkedHashSet |
Need sorted order | TreeSet |
🧠 TL;DR
HashSet
= fast and unordered.LinkedHashSet
= still fast but preserves the order in which elements were added.