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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *