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

Java Collections.asLifoQueue: a Queue view with stack ordering

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

Collections.asLifoQueue exposes a Deque through Queue methods while inserting and removing at its front.

Read the adapter's order

A caller may see a Queue type and assume first-in, first-out behavior. This adapter deliberately provides last-in, first-out order: the second added task is removed first. The view and backing deque share contents, so a mutation through either reference is immediately visible through the other.

The fixture uses LinkedList as the backing deque so the order is easy to inspect. For a non-null stack workload, ArrayDeque is often a better starting point; choose based on the actual null and memory contracts.

Keep the view private when ordering matters

Code with direct access to the underlying deque can add at either end and defeat the ordering assumptions of clients holding only the Queue view. Encapsulate both references behind one application API if task order is a correctness rule.

Working program

Java
import java.util.*;

public class UrgentTaskStackView {
    public static void main(String[] args) {
        Deque<String> taskDeque = new LinkedList<String>();
        Queue<String> urgentTasks = Collections.asLifoQueue(taskDeque);
        urgentTasks.add("batch-17");
        urgentTasks.add("batch-47");
        System.out.println(urgentTasks.remove());
        System.out.println(taskDeque);
    }
}

Output

Output
batch-47
[batch-17]

Cost and ownership

Endpoint operations on this LinkedList-backed view use constant structural work per call, while each node occupies separate storage. The view adds no independent queue; both references own access to the same mutable state.

Common Mistakes

  • Do not infer FIFO ordering solely from the Queue interface.
  • Do not treat the view as an independent copy.
  • Do not expose the backing deque when external endpoint writes would violate ordering.

Read next

Java LinkedList: operations, internals and failure cases, Java ArrayDeque for queues and stacks, Java Deque empty operations: choose return values or exceptions, Java collection views: live wrappers, snapshots and shallow copies.

java
collections
collections-lifo-queue-deque
Storage details