Course contentsShow
← Java
Lesson 1205 of 2,87027. Queue and Deque ImplementationsFree lesson

Removing Elements: removeFirst, removeLast, pollFirst, pollLast

Methods for removing elements from both ends and handling empty deques with poll vs remove behavior.

Removing Elements from ArrayDeque

You'll learn how to safely remove elements from both ends of an ArrayDeque and understand the difference between exception-throwing and null-returning removal methods.

Core Removal Operations

ArrayDeque provides four key methods for removing elements from either end of the deque:

  • removeFirst() – Removes and returns the first element; throws NoSuchElementException if empty
  • removeLast() – Removes and returns the last element; throws NoSuchElementException if empty
  • pollFirst() – Removes and returns the first element; returns null if empty
  • pollLast() – Removes and returns the last element; returns null if empty

Exception vs Null Behavior

The difference mirrors what you learned with Queue methods:

Exception-throwing methods (remove*) are useful when an empty deque is an error condition you want to catch immediately. If you try to remove from an empty deque, the exception alerts you to the problem.

Null-returning methods (poll*) are better when an empty deque is an expected, normal situation. You can check for null and handle it gracefully without try-catch blocks.

ArrayDeque<String> deque = new ArrayDeque<>();
deque.addFirst("Alice");
deque.addLast("Bob");

String first = deque.removeFirst();  // "Alice"
String last = deque.pollLast();       // "Bob"

// deque is now empty
String empty = deque.pollFirst();     // returns null (safe)
// deque.removeFirst();               // would throw NoSuchElementException

Choosing the Right Method

Use removeFirst/removeLast when you're certain the deque has elements, or when an empty deque indicates a bug. Use pollFirst/pollLast when emptiness is expected (like processing tasks until none remain).

Key Takeaway: removeFirst/removeLast throw exceptions on empty deques, while pollFirst/pollLast return null—choose based on whether emptiness is an error or an expected condition.