What is the ArrayDeque.removeLast 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 class of the Deque interface. ArrayDeque can be used as both Stack or Queue. Null elements are prohibited.

removeFirst method

The removeLast method gets and removes ArrayDeque object’s last element.

Syntax

public E removeLast()

Parameters

This method doesn’t take any parameters.

Return value

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

This method is the same as pollLast method except the pollLast method doesn’t throw NoSuchElementException if the deque is empty.

Code

The code below demonstrates the use of the removeLast method.

import java.util.ArrayDeque;
class RemoveLast {
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.removeLast() returns : " + arrayDeque.removeLast());
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 arrayDeque object’s add method to add three elements("1","2","3") to Deque.

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

Free Resources