w3resource

Java ArrayDeque Class: removeLast() Method

public E removeLast()

The removeLast() method is used to retrieve and remove the last element of a given deque. This method differs from pollLast only in that it throws an exception if this deque is empty.

Package: java.util

Java Platform: Java SE 8

Syntax:

removeLast()

Return Value:

the tail of this deque

Return Value Type: E - the type of elements held in this collection

Throws:

NoSuchElementException - if this deque is empty

Pictorial Presentation

Java ArrayDeque Class: removeLast() Method

Example: Java ArrayDeque Class: removeLast() Method

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
   public static void main(String[] args) {
      
      // Create an array deque 
      Deque<Integer> deque = new ArrayDeque<Integer>(8);

      // Use add() method to add elements in the deque
      deque.add(100);
      deque.add(200);
      deque.add(150);
      deque.add(95);  
      deque.add(200); 

      // Print all the elements of the original deque
      System.out.println("Elements of the original deque:");
      for (Integer number : deque) {
         System.out.println("Number = " + number);
      }

     // removeLast() removes element at last position
      int rv  = deque.removeLast();
      System.out.println("Element removed is: " + rv);


      // Print all the elements available in deque after pushing two elements using removeFirst()
      System.out.println("New deque:");
      for (Integer number : deque) {
         System.out.println("Number = " + number);
      }
   }
}

Output:

Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Number = 200
Element removed is: 200
New deque:
Number = 100
Number = 200
Number = 150
Number = 95

Java Code Editor:

Previous:removeFirstOccurrence Method
Next:removeLastOccurrence Method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-tutorial/util/arraydeque/java_arraydeque_removelast.php