Queue and Deque: ArrayDeque as stack and queue
FIFO queues, LIFO stacks, and why ArrayDeque replaces both Stack and LinkedList.
Queue: first-in, first-out
Queue<E> exposes two sets of methods for each operation — one that throws on failure and one that returns a sentinel:
| Operation | Throws | Returns null/false |
|---|---|---|
| Insert | add(e) | offer(e) |
| Remove head | remove() | poll() |
| Inspect head | element() | peek() |
Prefer offer/poll/peek — they communicate failure via return value rather than an exception, which is more useful in conditional logic.
Deque: double-ended queue
Deque<E> extends Queue and adds operations at both ends. ArrayDeque is the recommended concrete class:
// Used as a QUEUE (FIFO):
Deque<String> queue = new ArrayDeque<>();
queue.offer("first");
queue.offer("second");
String head = queue.poll(); // "first"
// Used as a STACK (LIFO):
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); // addFirst
stack.push(2); // addFirst
int top = stack.pop(); // 2 — removeFirst
int peek = stack.peek(); // 1 — peekFirst
Prefer ArrayDeque over Stack and LinkedList:
- java.util.Stack extends Vector (a legacy synchronized class from Java 1.0). It is effectively deprecated for new code.
- Using LinkedList as a queue works but ArrayDeque has better cache locality and is generally faster.
- ArrayDeque is the modern, unsynchronized, unbounded alternative for both stack and queue use cases.