CodeBlanks Logo Icon CodeBlanks

Queue and Deque

Learn queues with Queue<E> and Deque<E>.

The Queue<E> interface

Queue<E> is a first-in-first-out (FIFO) order. ArrayDeque is the fastest concrete implementation: Queue<String> todo = new ArrayDeque<>();.

offer(e) appends to the tail, poll() removes and returns the head, peek() returns the head without removing it. If the queue is empty, poll and peek return null; remove throws an exception.

Deque: a double-ended queue

Deque<E> (double-ended queue) allows add and remove at both ends. ArrayDeque implements both Queue and Deque. Methods: addFirst(e), addLast(e), removeFirst(), removeLast(), peekFirst(), peekLast().

For example a browser back/forward simulation uses addLast for forward and removeLast for back. When a stack is needed, push/pop also work on a Deque; the old Stack class is replaced by ArrayDeque.

Practice Build a todo queue

Declare Queue<String> todo = new ArrayDeque<>();. Add two tasks with todo.offer("Send email"); and todo.offer("Meeting");. Pull the first task with String first = todo.poll(); and print it with System.out.println(first);. Print the remaining count with System.out.println(todo.size());.

Starter code

Main.java
import java.util.Queue;
import java.util.ArrayDeque;

public class Main {
    public static void main(String[] args) {
        // Declare Queue<String>, add two tasks, poll first and print, print remaining count

    }
}

Sample solution

Main.java
import java.util.Queue;
import java.util.ArrayDeque;

public class Main {
    public static void main(String[] args) {
        Queue<String> todo = new ArrayDeque<>();
        todo.offer("Send email");
        todo.offer("Meeting");
        String first = todo.poll();
        System.out.println(first);
        System.out.println(todo.size());
    }
}

Expected output

Send email
1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the queue-add call

Question
todo.____("Send email");
Answer
todo.offer("Send email");

Explanation: The offer method appends an element to the queue tail.

2 What does todo.poll() do?

  • Removes and returns the head Correct answer
  • Only peeks at the head
  • Appends an element to the tail
  • Empties the queue

Explanation: poll removes and returns the head; returns null if empty.

3 Match the Queue/Deque methods

Term Meaning
offer(e) Appends to tail
poll() Removes the head
peek() Shows the head
addFirst(e) Adds to head

All lessons in Intermediate