What is the ArrayDeque.pollFirst 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 pollFirst method of ArrayDeque?

The pollFirst method can be used to get and remove the first element of an ArrayDeque object.

Syntax

public E pollFirst()

Parameters

This method doesn’t take any argument.

Return value

This method retrieves and removes the first element of the deque object. If the deque object is empty, then null is returned.

Code

The code below demonstrates how to use the pollFirst method.

import java.util.ArrayDeque;
class PollFirst {
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.pollFirst() returns : " + arrayDeque.pollFirst());
System.out.println("The arrayDeque is " + arrayDeque);
}
}

Explanation

In the above code:

  • In line number 1, we imported the ArrayDeque class.

  • In line number 4, we created an ArrayDeque object with the name arrayDeque.

  • From line number 5 to 7, we used the add() method of the arrayDeque object to add three elements ("1","2","3") to deque.

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

Free Resources