What is the LinkedList.removeLast() method in Java?

What is LinkedList?

A linked list is a collection of linear data elements. Each element (or node) contains a data part and a reference part.

The data part has the value and the reference part has the address link to the next element.

The elements are not indexed, so random access like in Array objects is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList class is the doubly-linked listA kind of linked list. Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. implementation of the List and Deque interfaces. The LinkedList class is present in the java.util package.

What is the removeLast() method of LinkedList class?

The removeLast() method can be used to remove the last element of a LinkedList object.

Syntax

The syntax of the removeLast() method is as follows:

public E removeLast();

Parameters

This method doesn’t take any argument.

Return Value

This method removes and returns the last element of the specified LinkedList. If the list is empty, then the NoSuchElementException exception is thrown.

Code

The code below demonstrates how to use the removeLast() method:

import java.util.LinkedList;
class LinkedListRemoveLast {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("The list is " + list);
System.out.println("Removing last element of the list : " + list.removeLast());
System.out.println("The list is " + list);
}
}

Explanation

In the above code:

  • In line 1, we import the LinkedList class.
import java.util.LinkedList;
  • In line 4, we create a LinkedList object with the name list.
LinkedList<String> list = new LinkedList<>();
  • From lines 5 to 7, we use the add() method of the list object to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
  • In line 10, we use the removeLast() method of the list object to remove and return the last element of the list.
list.removeLast(); // "3"

Free Resources