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.
1 |
public E remove(int index) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.javacodeexamples.collections.arraylist; import java.util.ArrayList; public class JavaArrayListRemoveLastElementExample { public static void main(String[] args) { //create ArrayList ArrayList<String> aListColors = new ArrayList<String>(); //add some elements aListColors.add("Yellow"); aListColors.add("Green"); aListColors.add("Blue"); aListColors.add("Brown"); /* * To remove last element of ArrayList * use remove method. */ //make sure to check the size first if( aListColors.size() > 0 ) aListColors.remove( aListColors.size() - 1 ); //print ArrayList System.out.println(aListColors); } } |
Output
1 2 |
Last element is removed from ArrayList [Yellow, Green, Blue] |
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.
Thank you. I’ve been missing the arraylist size>0 condition
Glad I could help.