What is the ArrayDeque.push method in Java?
An
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 ArrayDeque Array Double Ended Queue Dequeinterface.ArrayDequecan be used as a stack or queue.Nullelements are prohibited.
What is the push method of ArrayDeque?
The push method can be used to add an element to the beginning/front of the ArrayDeque object.
Syntax
public void push(E e);
This method takes the element to be added as an argument. If the argument is null, then a NullPointerException is thrown.
This method doesn’t return any value.
Code
The code below demonstrates how to use the push method.
import java.util.ArrayDeque;class Push {public static void main( String args[] ) {ArrayDeque<String> arrayDeque = new ArrayDeque<>();arrayDeque.push("3");System.out.println("The arrayDeque is " + arrayDeque);arrayDeque.push("2");System.out.println("The arrayDeque is " + arrayDeque);arrayDeque.push("1");System.out.println("The arrayDeque is " + arrayDeque);}}
Explanation
In the code above:
-
In line 1, we import the
ArrayDequeclass. -
In line 4, we create an
ArrayDequeobject with the namearrayDeque. -
In line 5, we use the
pushmethod of thearrayDequeobject to add an element ("3") to the beginning of thedequeand print it. -
In line 8, we use the
pushmethod to add an element ("2") to the beginning of thedequeand print it. -
In line 11, we use the
pushmethod to add an element ("1") to the beginning of thedeque.