Java NoSuchElementException
Removing the first element from an empty deque throws NoSuchElementException. pollFirst can represent an empty queue with null.
A simple example
NoSuchElementException
- Start with Queue containing no items
- Do this Request the first item
- Result No item available
Syntax
queue.removeFirst()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCall the next person at the clinic
A receptionist calls patients from the morning queue. If the final patient has already checked in, the screen should display an empty-queue message instead of trying to issue another number.
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
class Main {
public static void main(String[] args) throws Exception {
var patients = new ArrayDeque<String>();
try {
System.out.println(patients.removeFirst());
} catch (NoSuchElementException empty) {
System.out.println("No patients waiting");
}
}
}
No patients waiting
The queue contains zero patients. The receptionist can keep the window open without inventing a ticket.
Check for walk-ins without throwing
A clinic checks the walk-in queue between appointments. The receptionist needs a clear idle status during quiet hours and a patient number when someone arrives.
import java.util.ArrayDeque;
class Main {
public static void main(String[] args) throws Exception {
var walkIns = new ArrayDeque<Integer>();
Integer ticket = walkIns.pollFirst();
System.out.println(ticket == null ? "Desk available" : ticket);
}
}
Desk available
pollFirst returns null on this empty ArrayDeque, so a quiet shift is a normal branch.
Call a waiting pupil
The music desk has one pupil in its equipment queue. Take the next name from the queue. An empty queue should send the desk back to waiting.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
new ArrayDeque<>(List.of("Mila")).removeFirst();
System.out.println("Visitor ready");
} catch (NoSuchElementException problem) {
System.out.println("Wait for next visitor");
}
}
}
Visitor ready
What to watch for
Choose the removal method according to whether an empty queue is expected. ArrayDeque prohibits null elements.