Java ArrayDeque as a queue
Choose queue operations with explicit empty-queue behavior.
On this page
Generics and collection methods.
- Choose queue operations with explicit empty-queue behavior.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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());
}
}build test null
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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()); }}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 |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
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.