The Plain Picture#
Queue — the line at a ticket counter: first in, first out.
Stack — a pile of plates: last in, first out; you only touch the top.
Deque ("deck") — a line where you can join or leave at either end.
The Real Names#
FIFO (first in, first out) = queue. LIFO (last in, first out) = stack.
Deque<E>(double-ended queue) supports both.ArrayDequeis the implementation to use for both stacks and queues: a circular array (a head index and a tail index that wrap around the end of the array), all end operations O(1) (amortized, with doubling growth).Don't use the old
Stackclass — it extendsVector, whose every method is synchronized (slow, and a leftover from Java 1.0), and it lets you insert in the middle, breaking the stack idea. Don't useLinkedListfor queues either (Ch 2's node costs).ArrayDequedoesn't allownullelements (becausenullis used to mean "empty" bypoll/peek).
Under the Hood#
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3); // push/pop/peek work on the FRONT
stack.pop(); // 3
stack.peek(); // 2
Deque<String> queue = new ArrayDeque<>();
queue.offer("A");
queue.offer("B");
queue.offer("C"); // offer adds at the BACK
queue.poll(); // "A" // poll removes from the FRONT
queue.peek(); // "B"
// rest [B, C]Two families of method names — one throws, one returns a special value:
| Action | Throws an exception if it can't | Returns null/false instead |
|---|---|---|
| add at back | add(e) | offer(e) |
| remove from front | remove() | poll() |
| look at front | element() | peek() |
new ArrayDeque<String>().poll(); // null
new ArrayDeque<String>().remove(); // NoSuchElementExceptionUse offer / poll / peek in DSA code and check for null or isEmpty(). The full Deque API also has offerFirst/offerLast,
pollFirst/pollLast, peekFirst/peekLast.
The circular array:
capacity 8: [ _ | _ | A | B | C | _ | _ | _ ]
↑head ↑tail poll() takes A and moves head right
after more offers wrap around:
[ F | G | _ | B | C | D | E | _ ] tail wrapped to the start; no shifting ever
↑tail ↑headDSA uses: stacks for matching brackets, undo, "next greater element" (monotonic stack), and turning recursion into a loop (Stacks, Queues and Monotonic Stacks (coming soon)); queues for BFS (Graphs I (coming soon)); deques for the sliding-window maximum.
Check yourself
4 questionsFIFO vs LIFO — which is a queue?
Show answerHide answer
FIFO.
Which class should you use for a stack in Java, and why not Stack?
Show answerHide answer
ArrayDeque — Stack is a synchronized legacy class based on Vector, slower and allowing non-stack operations.
poll() vs remove() on an empty deque?
Show answerHide answer
poll() returns null; remove() throws NoSuchElementException.
How does ArrayDeque avoid shifting elements when you remove from the front?
Show answerHide answer
It's a circular array: the head index moves forward and wraps around instead of moving elements.