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

Adding Elements: addFirst, addLast, offerFirst, offerLast

Methods for adding elements to both ends of an ArrayDeque and differences between add/offer variants.

Adding Elements: addFirst, addLast, offerFirst, offerLast

What You'll Learn

You'll learn the four methods for inserting elements at either end of an ArrayDeque and understand when each variant is most appropriate.

Core Methods for Adding Elements

Since ArrayDeque is a double-ended queue, you can add elements to both the front and back of the structure. Java provides four primary methods:

The add Methods

addFirst(E element) - Inserts an element at the front (head) of the deque
addLast(E element) - Inserts an element at the back (tail) of the deque

These methods throw an IllegalStateException if the deque is at capacity (though ArrayDeque grows automatically, so this rarely happens in practice).

The offer Methods

offerFirst(E element) - Inserts an element at the front of the deque
offerLast(E element) - Inserts an element at the back of the deque

These methods return false if the element cannot be added (instead of throwing an exception).

Add vs Offer: What's the Difference?

Think of it like a train with open seating:

  • add methods are like insisting on boarding — they'll throw an error if there's a problem
  • offer methods are polite requests — they simply tell you "sorry, can't do that" by returning false

For ArrayDeque specifically, since it automatically resizes, both variants typically succeed. However, the distinction matters for bounded queues where capacity limits exist.

Usage Pattern

Use addLast for standard queue behavior (FIFO), addFirst when you need stack-like behavior (LIFO), and their offer variants when you prefer boolean feedback over exceptions.

Key Takeaway: ArrayDeque provides four methods to add elements—addFirst/addLast throw exceptions on failure, while offerFirst/offerLast return false, giving you control over both ends of the deque.