What is the ArrayDeque.removeLast method in Java?
An 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
pollLastmethod except thepollLastmethod doesn’t throwNoSuchElementExceptionif thedequeis 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
ArrayDequeclass. -
In line 4, we create a
ArrayDequeobject namedarrayDeque. -
From line 5 to 7, we use
arrayDequeobject’s add method to add three elements("1","2","3") toDeque. -
In line 10, we use the
removeLast()method of thearrayDequeobject to get and remove the last element. In our case,3will be removed and returned.