Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ArrayDeque as a FIFO queue

Use `ArrayDeque` to add elements at the back, remove them from the front, and check how many are left or whether the queue is empty.

Version: Java SE 21

Syntax

public void addLast(E e)
public boolean isEmpty()
public E removeFirst()
public int size()

In Java SE 21, java.util.ArrayDeque<E> implements a double-ended queue (Deque) backed by an array that grows as needed. It is not a List and does not offer indexed access such as get(0). Adding at the back and removing from the front gives FIFO order: the element added first leaves first.

ArrayDeque.addLast, declared as public void addLast(E e), appends an element and returns no value (void). ArrayDeque does not allow null, so addLast(null) throws NullPointerException. ArrayDeque.removeFirst, called as removeFirst(), removes and returns the front element as type E. On an empty queue it throws NoSuchElementException. If an empty queue is an expected case and you prefer a null result to an exception, use pollFirst().

ArrayDeque.size (size()) returns the current element count as an int, not the capacity of the backing array. ArrayDeque.isEmpty (isEmpty()) returns true when there are no elements and false otherwise. Neither method changes the queue.

In single-threaded code, a while (!queue.isEmpty()) loop can call removeFirst() on each iteration to drain the queue. ArrayDeque is not thread-safe: the check and removal are separate operations and do not form an atomic operation without external synchronization.

Examples

import java.util.ArrayDeque;

public class Main {
    public static void main(String[] args) {
        ArrayDeque<String> queue = new ArrayDeque<>();
        queue.addLast("A");
        queue.addLast("B");
        System.out.println(queue.size());

        while (!queue.isEmpty()) {
            System.out.println(queue.removeFirst());
        }

        System.out.println(queue.size());
        System.out.println(queue.isEmpty());
    }
}

Result

2
A
B
0
true

The program prints `2`, then `A` and `B` in insertion order, and finally `0` and `true` once the queue is empty.

Related lessons

  • Java · Lesson 54 · Intermediate · Version: 2

Sources