What is the ArrayDeque.addFirst 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 a Stack or Queue. Null elements are prohibited.

What is the addFirst method?

The addFirst method of the ArrayDeque class can be used to add the element to the beginning of the ArrayDeque object.

Syntax

public void addFirst(E e);

This method takes the element to be added as an argument.

This method doesn’t return any value.

Code

The code below demonstrates how to use the addFirst method.

import java.util.ArrayDeque;
class AddFirst {
public static void main( String args[] ) {
ArrayDeque<String> arrayDeque = new ArrayDeque<>();
arrayDeque.addFirst("3");
System.out.println("The arrayDeque is " + arrayDeque);
arrayDeque.addFirst("2");
System.out.println("The arrayDeque is " + arrayDeque);
arrayDeque.addFirst("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 a ArrayDeque object with the name arrayDeque.

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

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

  • In line 11, we used the addFirst method to add an element ("1") to the beginning of the deque.

Free Resources