LinkedHashSet.addFirst and addLast can move an existing member to an encounter-order endpoint without creating a duplicate.
Java 21 LinkedHashSet.addFirst and addLast relocate existing elements
Treat membership and order separately
A Set still contains one occurrence of each equal element. The Java 21 endpoint methods can reposition that occurrence: addFirst moves a member to the front, and addLast moves it to the back. Ordinary add of an existing member does not express that relocation. This matters when a deduplicated processing queue also has a display or retry order.
The fixture moves one dispatch ID forward and another backward, then removes the last. The final size checks membership separately from order. A duplicate value is not a second node.
Use a mutable implementation deliberately
SequencedSet describes encounter order but does not promise that every implementation supports repositioning. LinkedHashSet does. If the application needs key/value pairs as well, LinkedHashMap endpoint placement provides the analogous map operation.
Element equality and hash codes must remain stable while stored in a hash-based set. Mutating fields used by hashCode can make a member unreachable through ordinary lookup even though iteration still shows it.
Working program
import java.util.LinkedHashSet;
import java.util.List;
public class ReorderDispatchIds {
public static void main(String[] args) {
LinkedHashSet<String> dispatchIds = new LinkedHashSet<>(
List.of("load-15", "seal-47", "ship-82"));
dispatchIds.addFirst("ship-82");
dispatchIds.addLast("load-15");
System.out.println(dispatchIds);
System.out.println(dispatchIds.removeLast());
System.out.println(dispatchIds.size());
}
}Output
[ship-82, seal-47, load-15]
load-15
2Cost and ownership
Repositioning does not allocate a second entry for an existing member. Hash-based membership operations are expected constant-time under ordinary hash distribution; iterating the order remains O(n).
Common Mistakes
- Do not expect two copies of the same set member after relocation.
- Do not assume every SequencedSet implementation supports endpoint mutation.
- Do not mutate fields used in an element's equality or hash code while it is in a hash set.
Read next
Java 21 LinkedHashMap.putFirst and putLast for explicit key order, Java LinkedHashMap: encounter order and a bounded cache model, Java 21 sequenced collections: endpoints and reversed views, Java collection factories: rejected updates and shallow element ownership.
