To get the last element in a Java list, you can use the `get()` method with the index of size minus one.
In this example,
numbers
with integer elements.get()
method with the index size() - 1
.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); numbers.add(50);
int lastElement = numbers.get(numbers.size() - 1);
System.out.println("Last element is: " + lastElement);
}
}
Last element is: 50
In this example,
names
with string elements.get()
method with the index size() - 1
.import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice"); names.add("Bob"); names.add("Charlie"); names.add("David");
String lastElement = names.get(names.size() - 1);
System.out.println("Last element is: " + lastElement);
}
}
Last element is: David
In this tutorial, we learned How to get Last Element in a List in Java language with well detailed examples.