CKTIS / Java
Java FIFO queues: add, remove, and isEmpty
Add items to the tail of a FIFO queue, take them from the head, and check that the queue is not empty before calling `remove()`.
Version: Java SE 21
Syntax
import java.util.ArrayDeque;
import java.util.Queue;
// Method signatures available through Queue<E>:
boolean add(E e)
E remove()
boolean isEmpty()
// Example calls inside a method:
Queue<String> queue = new ArrayDeque<>();
queue.add("A");
while (!queue.isEmpty()) {
String next = queue.remove();
System.out.println(next);
}In Java SE 21, java.util.Queue<E> is the queue interface, and java.util.ArrayDeque<E> is the implementation used here. In this usage it behaves as a FIFO queue: the first item added is the first removed. Queue itself does not guarantee FIFO; a priority queue can choose its head by a different rule. The shorthand Queue.add/remove/isEmpty refers to the three methods below.
boolean add(E e) inserts an item and returns true on success. In a FIFO queue it inserts at the tail. If a capacity-restricted queue has no room, add(e) throws IllegalStateException, whereas offer(e) returns false in that case. ArrayDeque grows as needed but does not accept null elements.
E remove() takes no argument: it removes and returns the head, or throws NoSuchElementException if the queue is empty. Do not confuse it with boolean remove(Object o), inherited from Collection<E>: when supported, that overload removes one matching item if present and reports whether it removed anything. Like remove(), poll() removes and returns the head, but it returns null rather than throwing when the queue is empty.
boolean isEmpty() is inherited from Collection<E> and returns true only when the queue contains no items; it does not change the queue. The ! operator negates that result, so while (!queue.isEmpty()) checks that there is an item before each remove(). This guard works in the single-threaded example. Checking and removing are two separate operations, not one atomic operation; ArrayDeque itself is not thread-safe.
Examples
import java.util.ArrayDeque;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();
queue.add("A");
queue.add("B");
queue.add("C");
while (!queue.isEmpty()) {
System.out.println(queue.remove());
}
System.out.println(queue.isEmpty());
}
}Result
A B C true
The program prints `A`, `B`, and `C` in insertion order. After `C` is removed, the loop condition becomes false, so `remove()` is not called again. The last line, `true`, confirms that the queue is empty.
Related lessons
- Java · Lesson 22 · Intermediate · Version: 2