tags:

views:

5969

answers:

6

Hi,

How can I get the last value of arrayList (e.g. I dont know the last index of the ArrayList)?

Thanks.

+19  A: 

this should do it:

if (!arrayList.isEmpty()) {
  arrayList.get(arrayList.size()-1);
}
Henrik Paul
+10  A: 

The following is part of the List interface (which ArrayList implements):

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

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

Johannes Schaub - litb
+1  A: 

The size() method returns the number of elements in the ArrayList. The index values of the elements are 0 through (size()-1), so you would use myArrayList.get(myArrayList.size()-1) to retrieve the last element.

Ken Paul
A: 

how about the "count" ? cant we use it like "count-1" ?

kommradHomer
A: 

I used this statement(arraylist.get(arraylist.size()-1)) in my program.But I didn't get the last element of the arraylist.What I have to do?

shiva
A: 

if you modify your list, then use listiterator() and iterate from last index (that is size()-1 respectively). if you fail again, check your list structure.

dae