Java Get Last Element in List

To access the elements at the end of the List, you can use the get() method of the List, combined with the size() method to get the last element. Here is an example code:

List<String> list = new ArrayList<>();
list.add("Element 1");
list.add("Element 2");
list.add("Element 3");

// 获取最后一个元素
String lastElement = list.get(list.size() - 1);
System.out.println("最后一个元素是:" + lastElement);

In the code above, we first created a List with three elements, then used the get() method and size() method to retrieve the last element. By subtracting 1 from the size(), we can obtain the index of the last element in the List.

bannerAds