What is the ArrayDeque.offerFirst method in Java?
An Deque interface.
ArrayDequecan be used both as a stack or queue.Nullelements 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
ArrayDequeclass. -
In line 4, we created an
ArrayDequeobject with the namearrayDeque. -
In line 5, we used the
offerFirstmethod of thearrayDequeobject to add an element ("2") to the beginning of thedeque. Then, we printed it. -
In line 8, we used the
offerFirstmethod to add an element ("1") to the beginning of thedeque. Then, we printed it.