Java Utility Library

Java LinkedList - removeLast() Method



The java.util.LinkedList.removeLast() method is used to remove and return the last element of the list. Every removal of element results into reducing the list size by one unless the list is empty.

Syntax

public E removeLast()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the last element of the list.

Exception

Throws NoSuchElementException, if the list is empty.

Example:

In the example below, the java.util.LinkedList.removeLast() method is used to remove and return the last element of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedlist
    LinkedList<Integer> MyList = new LinkedList<Integer>();

    //populating linkedlist 
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    //printing linkedlist in reverse order
    System.out.print("MyList contains: ");
    while(MyList.size() != 0) {
      System.out.print(MyList.removeLast()+ " ");
   }
  }
}

The output of the above code will be:

MyList contains: 30 20 10 

❮ Java.util - LinkedList