Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Queue — inserting, inspecting, and retrieving elements

The java.util.Queue interface describes a queue of elements awaiting processing. Learn how offer differs from add and poll differs from remove, how peek inspects the head, and how isEmpty checks whether the queue contains elements.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Queue<E> queue = new ArrayDeque<>();
boolean inserted = queue.offer(e);
boolean added = queue.add(e);
E head = queue.peek();
E next = queue.poll();
E removed = queue.remove();
boolean empty = queue.isEmpty();

java.util.Queue<E> is a collection interface for holding elements awaiting processing. The head is the next element to retrieve. Ordering depends on the implementation: ArrayDeque used through the Queue API follows FIFO (first in, first out), but the interface itself does not guarantee FIFO.

Queue.offer(e) returns true after insertion, or false when a capacity restriction prevents insertion. Queue.add(e) returns true on success but throws IllegalStateException when no space is available. offer is not exception-free: an ineligible element can still cause an exception.

Queue.peek() reads the head without removing it; Queue.poll() reads and removes it. Both return null for an empty queue. No-argument Queue.remove() also retrieves and removes the head, but throws NoSuchElementException for an empty queue. Do not confuse it with inherited remove(Object), which removes a specified element. Queue.isEmpty(), inherited from Collection, returns true when the queue contains no elements.

Do not insert null: it conflicts with the empty-queue marker; ArrayDeque prohibits it. ArrayDeque is not thread-safe. Checking isEmpty() alone does not protect a later retrieval against a change by another thread.

Examples

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

public class QueueDemo {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayDeque<>();
        System.out.println(queue.offer("A"));
        System.out.println(queue.add("B"));
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.remove());
        System.out.println(queue.isEmpty());
        System.out.println(queue.peek());
        System.out.println(queue.poll());
    }
}

Result

true
true
A
A
B
true
null
null

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources