What is the ArrayDeque.poll 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 of the Deque interface. ArrayDeque can be used as a stack or queue. Null elements are prohibited.

The poll method

The poll method can be used to retrieve and remove the headfirst element of the ArrayDeque object.

Syntax

public E poll()

Parameters

This method does not take any arguments.

Return value

The poll() method retrieves and removes the head of the deque object. If the deque object is empty, then the method returns null.

Code

The code below demonstrates how to use the poll method.

import java.util.ArrayDeque;
class Poll {
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.poll() returns : " + arrayDeque.poll());
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 an ArrayDeque object with the name arrayDeque.

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

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

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources