Java ArrayList remove last element example

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

How to remove last element of ArrayList in Java?

To remove element from ArrayList, use remove method.

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

To remove last element from ArrayList, use size method along with remove method of ArrayList. size method returns 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, last element will be at list.size() – 1 index.


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

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

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

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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