We use the Deque.removeLast()
method to remove the element at the end of the deque. The method also returns the removed element.
The
Deque.removeLast()
method is present in theDeque
interface inside thejava.util
package.
Element removeLast(element)
The Deque.removeLast()
method doesn’t take any parameters.
The Deque.removeLast()
method returns the removed element from the deque
. removeLast()
throws an exception error if called on an empty deque.
Let us take a look at the code snippet below.
import java.util.*;class TestingRemoveLast{public static void main(String[] args){try{// Declare a DequeDeque<Integer> deque = new LinkedList<Integer>();// Add 7 integers to the dequedeque.add(212);deque.add(23);deque.add(621);deque.add(1280);deque.add(3121);deque.add(18297);deque.add(791);// Print the deque to check the successful insertion of the integersSystem.out.println("Elements in the deque are: "+deque);// call removeLast to check if the function works wellSystem.out.println("Calling removeLast() returns " + deque.removeLast());// call removeLast again to check if the function removes the last element successfullySystem.out.println("Calling removeLast() returns " + deque.removeLast());// Print the deque to check the remaining elementsSystem.out.println("Elements in the deque are: "+deque);// Call removeLast() 5 timesfor (int i=0; i<5; i++){System.out.println("Calling removeLast() returns " + deque.removeLast());}// Print the deque to check the remaining elementsSystem.out.println("Elements in the deque are: "+deque);// Call removeLast to test its functionality on an empty deque// This call throws an exception which is caught in the catch blockSystem.out.println("Calling removeLast() returns " + deque.removeLast());}catch(Exception error){// The exception details are printed hereSystem.out.println("Exception occurred: " + error);}}}
In line 9, we declare a deque that consists of Integer
type elements.
In lines 11-17, we use the Deque.add()
method to insert elements in the deque.
In line 20, we print the deque with the current elements.
In lines 22-24, we call the removeLast()
method to remove the elements from the end of the deque.
In lines 29-32, we call the removeLast()
method to remove all other elements from the deque.
In line 40, we call the removeLast()
method on the empty deque. This line throws an exception error, which is caught in line 42.
In line 45, we print the caught exception and the error message NoSuchElementException
.