⚠️ Did you know? Starting with JDK 21,
LinkedHashSet
implements the newSequencedCollection
interface — allowing insertion at the start, end, and even reversing the collection!
This brings new power — and sometimes unexpected behavior — to a class that has long been predictable.
🧠 What Changed?
LinkedHashSet
is now:
✅ Ordered (like before)
✅ No duplicates (like before)
✅ Now supports:
addFirst(E)
addLast(E)
reversed()
getFirst()
getLast()
🧪 Example: A New Way to Add
Set<String> set = new LinkedHashSet<>();
set.add("A");
set.add("B");
((SequencedSet<String>) set).addFirst("Z");
System.out.println(set); // [Z, A, B]
Wait, what?! 😲 LinkedHashSet
at the front?
🔄 Reversing Collections
SequencedSet<String> reversed = ((SequencedSet<String>) set).reversed();
System.out.println(reversed); // [B, A, Z]
The reversed view is live, not a copy! Changes in one reflect in the other.
🤯 Why This Can Surprise You
Let’s say you’ve always assumed LinkedHashSet
maintains insertion order and doesn’t allow element repositioning...
Suddenly, calling addFirst()
breaks that assumption.
myMethod(Set<String> values) {
values.add("X");
}
If someone passes a LinkedHashSet
with addFirst()
logic inside, the method might change order unexpectedly. 🚨
🧰 Best Practices
- 🔍 Be aware of runtime type when accepting
Set
interfaces - 📖 Check whether your code expects pure insertion order — now it may not be guaranteed!
- 🧪 When migrating to JDK 21+, review any code depending on
LinkedHashSet
ordering
🧵 TL;DR
Feature | Old LinkedHashSet
|
New LinkedHashSet (JDK 21+) |
---|---|---|
Maintains order | ✅ Yes | ✅ Yes |
No duplicates | ✅ Yes | ✅ Yes |
addFirst() |
❌ No | ✅ Yes |
reversed() |
❌ No | ✅ Yes |
👋 Final Thoughts
Java’s evolution with SequencedCollection adds great flexibility — but with power comes surprises. If you're using JDK 21 or newer, check your assumptions about the collections you're using!
🔗 Let me know if you'd like a deep dive into SequencedMap
or custom implementations of SequencedCollection
next!