Deque offers endpoint operations that either report an empty container with null or throw NoSuchElementException.
Java Deque empty operations: choose return values or exceptions
This complete Java 8 program has a checked output. Compile it as the named public class, then run it without additional libraries.
Choose one failure shape
pollFirst returns null when an empty deque has no head; removeFirst throws. peekFirst and getFirst make the same distinction without removal. Which pair fits the caller depends on whether empty is ordinary control flow or a broken precondition.
This program uses ArrayDeque, which refuses null members. That makes a null poll result unambiguous. LinkedList can hold null, so a caller using its nullable methods must check emptiness separately. The null-head case shows the collision.
Do not confuse capacity with emptiness
offerFirst reports insertion acceptance as a boolean; addFirst may throw when a capacity-constrained deque refuses an insertion. ArrayDeque grows as required, so this example does not exercise a capacity limit. The failure behavior belongs to the implementation and workload, not just the method name.
Working program
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
public class DispatchDequeContracts {
public static void main(String[] args) {
ArrayDeque<String> pending = new ArrayDeque<>();
System.out.println("poll=" + pending.pollFirst());
try { pending.removeFirst(); }
catch (NoSuchElementException empty) { System.out.println("remove rejected"); }
pending.offerLast("receipt-37");
System.out.println("peek=" + pending.peekFirst());
System.out.println("take=" + pending.removeFirst());
}
}Output
poll=null
remove rejected
peek=receipt-37
take=receipt-37Costs and boundaries
These endpoint calls have amortized constant-time behavior for ArrayDeque. Memory grows with retained elements and backing-array capacity; this example is not a bounded work queue.
Common Mistakes
- Do not treat a null poll result as universally unambiguous across implementations.
- Do not handle an empty deque by catching every RuntimeException.
- Do not assume offer means a producer has durable acceptance.
Read next
Java ArrayDeque for queues and stacks, Java LinkedList null elements: an empty-head ambiguity, Java blocking queues: bounded capacity and backpressure.
