What is the ArrayDeque.offerFirst method in Java?

An ArrayDequeArray Double Ended Queue is a growable array that allows us to add or remove an element from both the front and back. This class is the implementation of the Deque interface.

ArrayDeque can be used both as a stack or queue. Null elements are prohibited.

The offerFirst method

The offerFirst method can be used to add an element to the front of the ArrayDeque object.

Syntax

public boolean offerFirst(E e)

Parameters

The offerFirst method takes the element to be added to the deque as a parameter. This method throws NullPointerException if the argument is null.

Return value

The offerFirst method returns true if the element is added to the deque. Otherwise, false is returned.

Code

The code below demonstrates how to use the offerFirst method.

import java.util.ArrayDeque;
class OfferFirst {
public static void main( String args[] ) {
ArrayDeque<String> arrayDeque = new ArrayDeque<>();
arrayDeque.offerFirst("2");
System.out.println("The arrayDeque is " + arrayDeque);
arrayDeque.offerFirst("1");
System.out.println("The arrayDeque is " + arrayDeque);
}
}

Explanation

In the code above:

  • In line 1, we imported the ArrayDeque class.

  • In line 4, we created an ArrayDeque object with the name arrayDeque.

  • In line 5, we used the offerFirst method of the arrayDeque object to add an element ("2") to the beginning of the deque. Then, we printed it.

  • In line 8, we used the offerFirst method to add an element ("1") to the beginning of the deque. Then, we printed it.