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();
list.add("one");
list.add("two");
list.add("three");
list.add("four");

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
if((list!=null)||(list.size()>0){
String lastElement=(String) list.get(list.size()-1);
}

No comments:

Post a Comment

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