Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Collections, From the Inside

    Queues, Stacks and ArrayDeque

    FIFO (first in, first out) — queue. LIFO (last in, first out) = stack.

    Chapter 8 of 114 min read

    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. ArrayDeque is 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 Stack class — it extends Vector, 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 use LinkedList for queues either (Ch 2's node costs).

    • ArrayDeque doesn't allow null elements (because null is used to mean "empty" by poll/peek).

    Under the Hood#

    Java
    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:

    ActionThrows an exception if it can'tReturns null/false instead
    add at backadd(e)offer(e)
    remove from frontremove()poll()
    look at frontelement()peek()
    Java
    new ArrayDeque<String>().poll(); // null
    
    new ArrayDeque<String>().remove(); // NoSuchElementException

    Use 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:

    Output
      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   ↑head

    DSA 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 questions
    1

    FIFO vs LIFO — which is a queue?

    Show answer

    FIFO.

    2

    Which class should you use for a stack in Java, and why not Stack?

    Show answer

    ArrayDeque — Stack is a synchronized legacy class based on Vector, slower and allowing non-stack operations.

    3

    poll() vs remove() on an empty deque?

    Show answer

    poll() returns null; remove() throws NoSuchElementException.

    4

    How does ArrayDeque avoid shifting elements when you remove from the front?

    Show answer

    It's a circular array: the head index moves forward and wraps around instead of moving elements.