Queues and deques
What you will learn
Queues hold items until processing, while deques let you work at both ends. Use ArrayDeque for a simple in-memory FIFO queue or LIFO stack, and PriorityQueue when the next item depends on priority rather than arrival order.
- Process a FIFO queue and a LIFO deque.
- Distinguish exception-based and sentinel-based queue operations.
- Drain a priority queue in priority order without relying on iteration order.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Process requests in arrival order
import java.util.*;public class Main {
public static void main(String[] args) { Queue<String> pending = new ArrayDeque<>(); pending.offer("R1"); pending.offer("R2"); System.out.println(pending.peek()); System.out.println(pending.poll()); System.out.println(pending.poll()); System.out.println(pending.poll()); }}Expected output:
R1R1R2nullpeek leaves R1 pending; poll removes each head. A third removal finds no task.
Rules and mental model
Queue<E> extends Collection<E>. FIFO means first in, first out; many queues use that policy, but Queue itself also permits other orderings. offer inserts, peek observes the head, and poll removes it. add may throw if capacity prevents insertion, whereas offer returns false in that case; other errors such as invalid elements can still throw. On an empty queue, peek/poll return null while element/remove() throw NoSuchElementException. Deque adds front/back operations: offerFirst/Last, pollFirst/Last, peekFirst/Last and throwing counterparts. push adds to the front and pop removes the front; pop throws when empty. ArrayDeque rejects null and grows as needed; most end operations are amortized constant-time. LinkedList supports queue/deque operations but allows null, which is best avoided in queues because it obscures the empty sentinel. PriorityQueue rejects null, serves the least item according to natural order or comparator, and permits duplicates. Equal-priority ties have no FIFO guarantee; add an explicit tie-breaker when required. Its iteration order is not guaranteed sorted. These ordinary implementations do not provide concurrent processing guarantees.
Undo the most recent action
import java.util.*;public class Main {
public static void main(String[] args) { Deque<String> undo = new ArrayDeque<>(); undo.push("draw"); undo.push("color"); System.out.println(undo.pop()); undo.offerLast("older import"); System.out.println(undo.pollFirst()); System.out.println(undo.pollLast()); System.out.println(undo.isEmpty()); }}Expected output:
colordrawolder importtruepush and pop share the front. The older imported action is placed at the opposite end.
Serve priority jobs with explicit tie-breaking
import java.util.*;public class Main { record Job(int priority, int sequence, String name) implements Comparable<Job> { public int compareTo(Job other) { int p = Integer.compare(priority, other.priority); if (p != 0) return p; int s = Integer.compare(sequence, other.sequence); return s != 0 ? s : name.compareTo(other.name); } } public static void main(String[] args) { Queue<Job> jobs = new PriorityQueue<>(); jobs.offer(new Job(2, 1, "Report")); jobs.offer(new Job(1, 2, "Alert")); jobs.offer(new Job(1, 3, "Backup")); while (!jobs.isEmpty()) System.out.println(jobs.poll().name()); }}Expected output:
AlertBackupReportLower priority numbers are served first. Sequence numbers resolve equal priorities without depending on heap layout.
Common mistakes
Do not loop over a PriorityQueue expecting sorted output. Drain it with poll, or copy it first if you need to preserve pending jobs. Never insert null to represent a missing task.
Practice
Use an ArrayDeque of strings as a work queue. Enqueue A and B at the tail, insert urgent U at the front, then drain the queue. Print each item and finally the result of polling the empty queue.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Queues and deques — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Which queue method reads without removing?
An ArrayDeque is empty. What does poll return?
After push(A) and push(B), what does pop return?
Which operation yields priority order when repeated on a nonempty PriorityQueue?
How can equal priorities follow arrival order?