Skip to content

Remove last element of the LinkedList in Java example

This example shows how to remove the last element of the LinkedList in Java. This example also shows removing the last element of the linked list using a couple of methods.

How to remove last element of the LinkedList in Java?

There are a couple of ways using which you can remove the last element of the LinkedList object in Java.

1. Using the removeLast method

You can use the removeLast method of the LinkedList class to remove the last element.

The removeLast method removes the last element of the linked list and returns it.

Output

2. Using the remove method

You can also use the remove method of the LinkedList class.

The remove method deletes the element at the specified index from the list.

Since the linked list in Java starts from index 0,  to delete the last element, pass the LinkedList size – 1 as the index in the remove method as given below.

Output

The remove method of the linked list size throws IndexOutOfBoundsException if the specified index is out of the range. That is if the specified index is less than zero or greater than or equal to the size of the linked list object.

In order to avoid this exception, it is necessary to check the linked list size before removing the last element using the remove method.

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.