CKTIS / Java
Deque — double-ended queue and stack
java.util.Deque<E> describes a double-ended queue: elements can be added and removed at either end. The same interface supports a FIFO queue and a LIFO stack; the methods you choose determine the behavior.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Deque<E> deque = new ArrayDeque<>();
boolean accepted = deque.offerLast(element);
deque.push(element);
E first = deque.pop();
boolean empty = deque.isEmpty();java.util.Deque<E> is a collection interface with a first and last end. A FIFO queue adds elements at the end and removes from the front; a LIFO stack adds and removes at the front. ArrayDeque<E> is the concrete implementation used in the example.
Deque.offerLast(e) adds at the end and returns true on insertion, or false when a capacity restriction prevents insertion. This does not rule out exceptions for invalid elements. Deque.push(e) adds at the front like addFirst(e), returns void, and throws IllegalStateException if no space is available.
Deque.pop() removes and returns the first element like removeFirst(); it throws NoSuchElementException when empty. pollFirst() returns null instead. Deque.isEmpty() returns true when there are no elements. Checking emptiness before removal is not an atomic operation.
ArrayDeque grows as needed, prohibits null, and is not thread-safe without external synchronization. In the example, adding A, B, and then calling push("C") produces the front-to-back order C, A, B. Mixing these insertion styles does not produce a pure LIFO stack for all elements.
Examples
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
System.out.println(deque.offerLast("A"));
deque.offerLast("B");
deque.push("C");
while (!deque.isEmpty()) {
System.out.println(deque.pop());
}
System.out.println(deque.isEmpty());
}
}Result
true C A B true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.