What is the ArrayDeque.removeFirst method in Java?

An ArrayDequeArray Double Ended Queue is a growable array that adds or removes an element from both the front and the back. This class is the implementation of the Deque interface. ArrayDeque can be used as both Stack or Queue. Null elements are prohibited.

removeFirst method

The removeFirst method gets and removes the first element of the ArrayDeque object.

Syntax

public E removeFirst()

Parameters

This method doesn’t take any parameters.

Return value

This method retrieves and removes the first element of the Deque object. If the Deque object is empty then NoSuchElementException is thrown.

This method is the same as the pollFirst method except that the pollFirst method doesn’t throw NoSuchElementException if the Deque is empty.

Code

The code below demonstrates the use of the removeFirst method:

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

Explanation

In the code above:

  • In line 1, we import the ArrayDeque class.

  • In line 4, we create a ArrayDeque object named arrayDeque.

  • From line 5 to 7, we use the arrayDeque object to add three elements("1","2","3") to Deque.

  • In line 10, we use the removeFirst() method of the arrayDeque object to get and remove the first element. In our case, 1 will be removed and returned.

Free Resources