Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java 21 Deque.reversed: translate head and tail mutations

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Deque.reversed supplies a reverse-ordered deque view, so its head is the backing deque's tail.

Read operations from the view's orientation

Adding at the view's front appends at the backing deque's end. Polling the view's last element removes the backing deque's first. This translation is visible with ArrayDeque and does not require copying every queued item.

A queue consumer may expect pollFirst to mean oldest work. Passing it a reversed view changes that meaning. Name the orientation at an API boundary instead of accepting an arbitrary Deque and assuming the head is always the intake side.

Retain the container's element rules

ArrayDeque forbids null elements. That keeps a null poll result usable as an empty signal. LinkedList can contain null, so the same signal is ambiguous there. A reversed view inherits the underlying deque's element and concurrency constraints; it does not sanitize them.

For a read-only backward pass through LinkedList, descendingIterator is enough. Use a reversed Deque when the caller intentionally needs the inverse endpoint operations.

Working program

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class ReverseDispatchDeque {
    public static void main(String[] args) {
        Deque<String> dispatches = new ArrayDeque<>();
        dispatches.addLast("load-15");
        dispatches.addLast("seal-47");
        Deque<String> reverse = dispatches.reversed();
        reverse.addFirst("ship-82");
        System.out.println(dispatches);
        System.out.println(reverse.pollLast());
        System.out.println(dispatches);
    }
}

Output

Output
[load-15, seal-47, ship-82]
load-15
[seal-47, ship-82]

Cost and ownership

The reversed view avoids copying the deque. ArrayDeque endpoint operations are amortized O(1), while traversal is O(n). The view shares all elements and mutation state with its backing deque.

Common Mistakes

  • Do not treat a reversed deque head as the original intake head.
  • Do not insert null into ArrayDeque.
  • Do not assume a view is an independently synchronized queue.

Read next

Java ArrayDeque for queues and stacks, Java Deque empty operations: choose return values or exceptions, Java 21 LinkedList.reversed: write-through order and endpoint edits, Java LinkedList null elements: an empty-head ambiguity.

java
collections
deque-reversed-orientation
Storage details