DEV Community

araf
araf

Posted on • Edited on

πŸš€ Java Surprise: LinkedHashSet Now Implements SequencedCollection!

⚠️ Did you know? Starting with JDK 21, LinkedHashSet implements the new SequencedCollection 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]
Enter fullscreen mode Exit fullscreen mode

Wait, what?! 😲 LinkedHashSet at the front?


πŸ”„ Reversing Collections

SequencedSet<String> reversed = ((SequencedSet<String>) set).reversed();
System.out.println(reversed); // [B, A, Z]
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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!



Enter fullscreen mode Exit fullscreen mode

Top comments (0)