There are times when we need to get the last element of an ArrayList, this gets difficult when we don’t know the last index of the list. In this tutorial we are going to see an example to get the last element from ArrayList.
Example: Getting the last element from List
import java.util.ArrayList; import java.util.List; public class ArrayListExample { public static void main(String[] args) { /* Creating ArrayList of Strings and adding * elements to it */ List<String> al = new ArrayList<String>(); al.add("Ajay"); al.add("Becky"); al.add("Chaitanya"); al.add("Dimple"); al.add("Rock"); // Displaying ArrayList elements System.out.println("ArrayList contains: "+al); // Logic to get the last element from ArrayList if (al != null && !al.isEmpty()) { System.out.println("Last element is:"); System.out.println(al.get(al.size()-1)); } } }
Output:
ArrayList contains: [Ajay, Becky, Chaitanya, Dimple, Rock] Last element is: Rock
Leave a Reply