Skip to main content
PreparationZone Logo
PrepZone

Queues, Deques and Priority Queues

Ends-first data structures, why ArrayDeque replaced Stack, and how a priority queue really orders.

Pass checkpoint below

Why this matters

  • ArrayDeque is the correct replacement for both Stack and LinkedList, and most code has not caught up.
  • Queue offers two methods for every operation — one throwing, one returning a sentinel — and picking the wrong one produces either noisy exceptions or silently ignored failures.
  • PriorityQueue's iteration order surprises nearly everyone the first time they print one.

Queue and Deque

Queue — FIFO
offer() → tail
poll() ← head
Deque — both ends
addFirst / addLast
pollFirst / pollLast
PriorityQueue — heap
Smallest leaves firstOrder of arrival ignored

Iteration order is not sorted — only polling is.

A queue serves the front, a deque serves either end, and a priority queue ignores arrival order and serves the smallest element first.
  • Queue is first-in-first-out. You add at the tail and remove from the head.
  • Deque — double-ended queue — allows adding and removing at both ends, so it serves as a queue and a stack.
  • ArrayDeque is a circular array implementation. It is the right default for both roles.
  • PriorityQueue is a binary heap; the head is always the smallest element by the ordering, not the oldest.

Two methods for every operation

Each queue operation comes in a throwing form and a sentinel-returning form.

AspectOperationThrowing vs returning
Add to tailadd(e) — throws if capacity-bound and fulloffer(e) — returns false
Remove from headremove() — throws NoSuchElementExceptionpoll() — returns null
Inspect headelement() — throws NoSuchElementExceptionpeek() — returns null
  • Add to tail

    Operationadd(e) — throws if capacity-bound and full
    Throwing vs returningoffer(e) — returns false
  • Remove from head

    Operationremove() — throws NoSuchElementException
    Throwing vs returningpoll() — returns null
  • Inspect head

    Operationelement() — throws NoSuchElementException
    Throwing vs returningpeek() — returns null

Prefer the sentinel forms. An empty queue is a normal state, not an error.

Java
Loading compiler…

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 4 sections

  • ArrayDeque as a stack
  • PriorityQueue
  • Blocking queues
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.