β οΈ 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!
Top comments (0)