Memra

Queue and Deque: ArrayDeque as stack and queue

◈ 4 cards

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:

OperationThrowsReturns null/false
Insertadd(e)offer(e)
Remove headremove()poll()
Inspect headelement()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.
used asaddremoveinspectQueue (FIFO)offer(e) → tailpoll() → headpeek() → headStack (LIFO)push(e) → headpop() → headpeek() → headpush is addFirst; offer is addLast.
One class, two disciplines, and the only difference is which end you add to. Both remove from the head — so adding at the head gives LIFO and adding at the tail gives FIFO.
NORMAL ~/memra/learn/java-from-zero/queue-deque-arraydeque utf-8 LF