LinkedList.reversed returns a reverse-ordered view whose endpoint mutations change the original list.
Java 21 LinkedList.reversed: write-through order and endpoint edits
Orient the endpoints
The first element of the reversed view is the last element of the backing list. An addFirst on that view therefore appends at the backing tail; removeLast removes the backing head. The view is not a copied sequence. Later edits to the backing list appear through the same view, and edits to the view write through.
This Java 21 method differs from descendingIterator, which only traverses the existing list backward. If a stable snapshot is required, copy the reversed view into a separate list and decide whether its mutable elements also need copying.
Do not infer thread safety
A view does not add synchronization. A structural edit while a second thread traverses either orientation still needs an ownership or locking rule. Fail-fast behavior is only a bug signal and cannot serve as a concurrency protocol.
The reversed view retains the backing list. Keeping the view alive keeps that collection reachable. For a short-lived report, copy boundaries may be more appropriate.
Working program
import java.util.LinkedList;
public class ReversedDispatchQueue {
public static void main(String[] args) {
LinkedList<String> dispatches = new LinkedList<>();
dispatches.add("load-47");
dispatches.add("seal-82");
LinkedList<String> reverse = dispatches.reversed();
reverse.addFirst("ship-15");
System.out.println(dispatches);
System.out.println(reverse);
System.out.println(reverse.removeLast());
System.out.println(dispatches);
}
}Output
[load-47, seal-82, ship-15]
[ship-15, seal-82, load-47]
load-47
[seal-82, ship-15]Cost and ownership
Constructing the view does not copy the list elements. Endpoint insertion and removal on LinkedList are constant-time operations; iteration over either orientation is O(n). The view and its backing list share one mutable structure.
Common Mistakes
- Do not call reversed a snapshot.
- Do not read addFirst on the reversed view as insertion at the backing head.
- Do not use fail-fast exceptions as a substitute for synchronization.
Read next
Java LinkedList descendingIterator: inspect and remove from the tail, Java 21 sequenced collections: endpoints and reversed views, Java LinkedList fail-fast iterators: a bug signal, not safety, list copyof element alias.
