Tuesday, November 22, 2011

Find last Element/Object of ArrayList

Most of the times we encountered the situation to read the first element of ArrayList using get(0) method. In Some instances you want to read the last element of anArray List, you can use the following code snippet.
ArrayList list=new ArrayList();

To Access the fourth object, we have to use list.get(list.size()-1). Here size() method returns the size of the list and size -1 return the last index of the list. Note:-
In runtime if there are no elements in the list,if you call method list.get(list.size()-1), it will throws IndexOutOfBoundsException. always make sure that you call this method if list is not empty or null check.
Here is the code snippet
String lastElement=(String) list.get(list.size()-1);


Note: Only a member of this blog may post a comment.