What is the ArrayDeque.offer 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 class of the Deque interface. ArrayDeque can be used as both Stack or Queue.

null elements are prohibited.

The offer method can be used to add an element to the end of the ArrayDeque object.

Syntax

public boolean offer(E e)

Parameters

The offer 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 offer method returns true if the element is added to the Deque. Otherwise, false is returned.

Code

The code below demonstrates how to use the offer method:

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

Explanation

In the above code:

  • In line 1, we import the ArrayDeque class.

  • In line 4, we create a ArrayDeque object with the name arrayDeque.

  • In line 5, we use the offer method of the arrayDeque object to add an element ("1") to the end of the Deque. Then, we print it.

  • In line 8, we use the offer method to add an element ("2") to the end of the Deque. Finally, we print it.

Free Resources