What is the ArrayDeque.pollLast method in Java?

An ArrayDeque (Array 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 a stack or queue. Null elements are prohibited.

What is the pollLast method of ArrayDeque?

The pollLast method can be used to get and remove the last element of the ArrayDeque object.

Syntax

public E pollLast()

Parameters

This method doesn’t take any arguments.

Return value

This method retrieves and removes the last element of the deque object. If the deque object is empty, then pollLast returns null.

Code

The code below demonstrates how to use the pollLast method.

import java.util.ArrayDeque;
class PollLast {
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.pollLast() returns : " + arrayDeque.pollLast());
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 dequeu.

  • In line 10: We use the pollLast() method of the arrayDeque object to get and remove the last element. In our case, 3 is removed and returned.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources