Lesson · Collections Framework
Queue & Deque: processing order as a data structure
16 min readQueue & Deque
Queues model who goes next: FIFO with ArrayDeque, both ends with Deque, and PriorityQueue's binary heap when the next item should be the smallest or most urgent rather than the oldest.
One contract, two personalities
Queue defines each operation twice. add / remove / element throw when the queue is full or empty; offer / poll / peek return false or null instead. The reason: polling an empty queue is a normal event at shutdown, so you want null, not an exception. Use the throwing trio to assert against bugs, the quiet trio in real flow.
Deque extends Queue with both ends: addFirst, addLast, pollFirst, pollLast. One structure, and suddenly it can be a FIFO queue, a LIFO stack and a sliding window at the same time.
Both ends: the four jobs of a Deque
Both ends are cheap on purpose: adding or removing at either end of an ArrayDeque is O(1) amortized, so picking an end is a design decision, not a performance trade-off. Step through the ring below and watch the head wrap around the back:
- FIFO task queue: offer (addLast) to enqueue, poll (pollFirst) to serve. Order of arrival is order of service.
- LIFO stack: push and pop both work at the front (addFirst and pollFirst). Same end in and out, which is why ArrayDeque replaced java.util.Stack.
- Sliding-window maximum: addLast admits the new element, pollLast drops smaller candidates from the back, pollFirst expires whatever leaves the window. Each element enters and leaves once, so a full scan is O(n).
- Work stealing: a busy worker pushes and pops at its own end; idle workers steal from the opposite end, so the hot end never contends. This is how ForkJoinPool keeps its queues cheap.
Same structure, four processing orders. Change the end, not the container.
Deque board · both ends of the ring
head = first element · tail = one past the last (the next free slot)
An ArrayDeque is a circular array (8 slots here) with two indices: head is the first element, tail is one past the last. Either index can wrap around the end.
ArrayDeque: the default queue and stack
ArrayDeque is a growable circular array: head and tail are two indices that wrap around, and both ends add and remove in O(1) amortized. No nodes, no pointers, contiguous memory. That is exactly why it beats LinkedList at the same job.
It also retired the legacy Stack class. stack.push() is deque.addFirst() and stack.pop() is deque.pollFirst(): same LIFO semantics, none of the synchronized baggage, better cache behaviour, and it no longer confuses you by being a Vector subclass.
ArrayDeque board · the ring grows
Ring: 4 slots
head = first element · tail = one past the last (the next store position)
A wrap in action: b, c and d sit at indices 1 to 3, and the tail has wrapped around to 0. Read head to tail: b → c → d.
Corner cases that bite
The Deque contract has sharp edges, and almost all of them are about the empty state or about null:
| Situation | What happens |
|---|---|
| pollFirst / pollLast / peekFirst / peekLast on empty | return null, no exception |
| removeFirst / removeLast / getFirst / getLast on empty | throw NoSuchElementException |
| add(null) on ArrayDeque | throws NullPointerException: null is the empty signal, so it cannot be stored |
| add(null) on LinkedList | accepted, so later a poll() returning null no longer means empty |
| contains / remove(Object) | O(n): walks the deque, checking both ends first |
| for-each order | head to tail; descendingIterator() walks it the other way |
| modify while iterating | ConcurrentModificationException (fail-fast iterator) |
| duplicates | allowed: a queue is not a Set |
| capacity | ArrayDeque doubles when full; switch to a BlockingQueue when you need a hard bound |
Most production bugs here are null bugs: a quiet poll() returning null is indistinguishable from a stored null, which is exactly why ArrayDeque forbids null.
PriorityQueue: order by importance, not by arrival
PriorityQueue stores elements in a binary heap: an array where each parent is smaller than its children (by natural order, or a Comparator you supply). offer and poll walk the element up or down the tree in O(log n). peek is O(1), because the smallest element sits at index 0.
It is not a sorted list. Iterating a PriorityQueue gives heap order, not sorted order. The array is only partially ordered by design, because that is cheaper to maintain. To consume in priority order, drain it with poll until empty; to see it sorted, sort a copy.
This is the structure behind Dijkstra's algorithm, top-k problems, k-way merges and schedulers, anywhere the answer to 'who is next?' is a comparison, not a timestamp. Also know its limits: no random access, no stable ordering among equal elements, and no efficient arbitrary removal.
Heap board · the tree inside the array
empty heap
A PriorityQueue is a binary min-heap inside a plain array: index i has children 2i+1 and 2i+2, and the parent of i sits at (i-1)/2. No node objects, no pointers: an array with a shape.
Where queues meet production
The java.util.concurrent family is this lesson grown up: BlockingQueue (ArrayBlockingQueue, LinkedBlockingQueue) blocks producers and consumers instead of asking them to poll. That is the backbone of thread pools: a pool is a BlockingQueue of tasks plus workers.
DelayQueue schedules by time-to-live; SynchronousQueue hands off directly between threads. You will meet those in the executors lesson; today's takeaway is that the interfaces up here are the ones those classes implement.
PriorityQueue iteration is not sorted
for-each and toArray() walk the internal heap array, which is only sifted enough to keep the minimum at index 0. So 1, 3, 2, 7 is a perfectly valid iteration of a priority queue whose poll order is 1, 2, 3, 7. Never print or iterate a PriorityQueue expecting sorted output; drain it with poll.
Interview angles
Why does Queue define operations twice: add/offer, remove/poll, element/peek?+
Failure policy. The throwing versions surface programming errors on a full or empty queue; the quiet versions return false/null because empty-poll is a normal control-flow event in servers and shutdowns. Standard practice: offer/poll/peek in normal flow.
Why ArrayDeque instead of Stack or LinkedList?+
Stack is a legacy synchronized Vector subclass: slower and easy to misuse. LinkedList pays a node allocation per element and chases pointers. ArrayDeque is a circular array: O(1) at both ends, cache-friendly, and it implements the same Deque contract.
How does PriorityQueue store its elements?+
A binary heap inside a plain array: index i has children 2i+1 and 2i+2. offer sifts up, poll swaps the last element to the root and sifts down, O(log n) each; peek is O(1). No random access, and iteration is heap order, not sorted order.
When would a PriorityQueue be the wrong tool?+
When you need all elements sorted (sort or a TreeSet/TreeMap), when equal elements must keep FIFO order (a heap is not stable), or when you need to remove an arbitrary element efficiently: a heap only removes the root well.
Why does ArrayDeque reject null elements?+
Because its poll and peek family signals emptiness with null. Storing a null would make a real element and an empty result indistinguishable, which is why add(null) throws. LinkedList allows null, and inherits exactly that ambiguity.
You need a fixed-capacity queue where producers wait when it is full. What do you reach for?+
A BlockingQueue: ArrayBlockingQueue for a fixed array, LinkedBlockingQueue for an optionally bounded linked one. put/take block instead of throwing or returning null. ArrayDeque itself is unbounded: it doubles when full.