Java · Course navigation

Java ArrayDeque as a queue

Choose queue operations with explicit empty-queue behavior.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1import java.util.ArrayDeque;
2import java.util.Queue;
3class 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading