Skip to content

Java ArrayList remove last element example

Java ArrayList remove last element example shows how to remove last element from ArrayList in Java. The example also shows how to avoid IndexOutOfBoundException while removing the last element from ArrayList.

How to remove last element of ArrayList in Java?

To remove an element from the ArrayList, use the remove method.

This method removes an element from ArrayList at the specified index. If you remove an element from the middle of the ArrayList, it shifts the subsequent elements to the left. The remove method also returns the element which was removed from the ArrayList.

To remove the last element from ArrayList, use the size method along with remove method of the ArrayList. The size method returns the number of elements contained in the ArrayList.

ArrayList index starts from 0, so the first element will be at index 0 in the ArrayList. Going by this, the last element will be at the ArrayList size – 1 index.

Output

Note: Please make sure that the size of the ArrayList is greater than 0. The remove method throws IndexOutOfBoundsException if the list is empty and an attempt is made to remove the element from it using size – 1.

As a good practice, always check the size of ArrayList before removing any element from it. The remove method throws IndexOutOfBoundsException if the specified index is less than 0 or index is greater than or equal to the size of the list.

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

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

About the author

2 comments

Leave a Reply

Your email address will not be published.