Why this matters
ArrayDequeis the correct replacement for bothStackandLinkedList, and most code has not caught up.Queueoffers 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.
Queueis 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.ArrayDequeis a circular array implementation. It is the right default for both roles.PriorityQueueis 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.
| Aspect | Operation | Throwing vs returning |
|---|---|---|
| Add to tail | add(e) — throws if capacity-bound and full | offer(e) — returns false |
| Remove from head | remove() — throws NoSuchElementException | poll() — returns null |
| Inspect head | element() — throws NoSuchElementException | peek() — returns null |
Add to tail
Operationadd(e) — throws if capacity-bound and fullThrowing vs returningoffer(e) — returns falseRemove from head
Operationremove() — throws NoSuchElementExceptionThrowing vs returningpoll() — returns nullInspect head
Operationelement() — throws NoSuchElementExceptionThrowing vs returningpeek() — returns null
Prefer the sentinel forms. An empty queue is a normal state, not an error.
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.