Java ArrayDeque as a queue
Choose queue operations with explicit empty-queue behavior.
Java
import java.util.ArrayDeque;
import java.util.Queue;
class Main {
public static void main(String[] args) {
Queue<String> jobs = new ArrayDeque<>();
jobs.offer("build");
jobs.offer("test");
System.out.println(jobs.poll());
System.out.println(jobs.poll());
System.out.println(jobs.poll());
}
}Output
build test null
Explanation
ArrayDeque can serve as a FIFO queue through offer and poll. offer adds at the tail, while poll removes the head or returns null if empty.
Returning null is different from remove(), which throws on an empty queue. ArrayDeque does not allow null elements, so null can unambiguously signal that no item was available.
Explore the dry run
Guided walkthroughReady
1
import java.util.ArrayDeque;2
import java.util.Queue;3
class Main {4
public static void main(String[] args) {5
Queue<String> jobs = new ArrayDeque<>();6
jobs.offer("build");7
jobs.offer("test");8
System.out.println(jobs.poll());9
System.out.println(jobs.poll());10
System.out.println(jobs.poll());11
}12
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Start an empty queue. | jobs = [] | — | |
| Enqueue build. | jobs = [build] | — | |
| Enqueue test behind it. | jobs = [build, test] | — | |
| First poll removes build. | jobs = [test] | build | |
| Second poll removes test. | jobs = [] | build test | |
| Third poll returns null because the queue is empty. | jobs = [] | build test null |
Cost and common mistakes
Amortized O(1) endpoint operations and O(n) storage.
- Do not auto-unbox a null Integer result from an empty queue.
- ArrayDeque is not a concurrent queue implementation.
Try it yourself
Use peek before the first poll. Does it remove build?
Reveal answer and reasoning
No. peek reads the head without removal, so the following poll still returns build.