Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (2.6k points)

How can I get the last value of an ArrayList?

I don't know the last index of the ArrayList.

1 Answer

0 votes
by (46k points)
edited by

To get the last value of an ArrayList use:

if (arrayList != null && !arrayList.isEmpty()) {

  T item = arrayList.get(arrayList.size()-1);

}

or use the syntax below which is a part of the List interface (which ArrayList implements):

E e = list.get(list.size() - 1);

E is the component type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...