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

First and Last Element Operations: addFirst, addLast, removeFirst, removeLast

Core deque operations for adding and removing elements at both ends, with exception-throwing behavior on failure.

First and Last Element Operations: addFirst, addLast, removeFirst, removeLast

You'll learn the four core Deque methods that give you precise control over adding and removing elements at either end.

Since a Deque (double-ended queue) allows access to both ends, Java provides explicit methods for each end. These are the exception-throwing variants — they throw exceptions when they can't complete their operation.

The Four Core Methods

addFirst(element) — Inserts an element at the front of the deque. Throws an exception if capacity restrictions prevent the addition.

addLast(element) — Inserts an element at the back of the deque. Throws an exception if the deque is full (for bounded deques).

removeFirst() — Removes and returns the first element. Throws NoSuchElementException if the deque is empty.

removeLast() — Removes and returns the last element. Throws NoSuchElementException if the deque is empty.

Why Exception-Throwing Matters

Unlike their cousins (offerFirst, offerLast, pollFirst, pollLast) which return false or null on failure, these methods fail loudly. This is useful when an empty deque or failed insertion represents a programming error you want to catch immediately.

Mental Model

Think of a deque like a horizontal line of people where you can add or remove from either the front or the back:

  • addFirst() — someone cuts to the front of the line
  • addLast() — someone joins at the back
  • removeFirst() — the front person leaves
  • removeLast() — the last person leaves

If the line is empty and you try to remove someone, you get an error (exception) because that's an invalid operation.

Key Takeaway: addFirst, addLast, removeFirst, and removeLast provide explicit, exception-throwing control over both ends of a Deque, making bugs obvious rather than silent.