EN
Java - remove last element from ArrayList
3 points
In this article, we would like to show you how to remove the last element from ArrayList in Java.
Quick solution:
xxxxxxxxxx
1
int last = myArrayList.size() - 1; // calculate index of last element
2
myArrayList.remove(last); // remove last element by index
In this example, we calculate the index of the last element in fruits ArrayList and remove it using remove()
method.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> fruits = new ArrayList<>();
7
8
// add items to the ArrayList
9
fruits.add("Apple");
10
fruits.add("Banana");
11
fruits.add("Cherry");
12
13
// calculate index of the last element
14
int last = fruits.size() - 1;
15
16
// remove last element by index
17
fruits.remove(last);
18
19
System.out.println(fruits); // [Apple, Banana]
20
}
21
}
Output:
xxxxxxxxxx
1
[Apple, Banana]