Search

Thursday, June 18, 2015

How to get first and last elements form ArrayList in Java

There are times when you need to get the first or last element of an ArrayList. One of the common scenario where you need first and last element of a list is suppose you have a sorted list and wants to get the highest and lowest element? How do you get that? The first element is your lowest and last element is your highest, provided ArrayList is sorted in ascending order. If its opposite then first element would be the maximum and last element would be the minimum. This is quite easy to do in ArrayList because the first element is stored at index 0 and last element is on index, size - 1. If you know how to get the size of ArrayList then you can easily get those two values. Just remember, that you need to use size() method and not length, which is used to get the length of array. Earlier we have seen how to get first and last element from linked list and In this tutorial we are going to see an example of how get the last element from ArrayList in Java.

By the way if you are serious about learning Java collection framework in deep and want to master different types of collection classes e.g. List, Set, Map, ConcurrentMap, Queue, Stack, BlockingQueue and other thread safe collections introduced on Java 5 and 6, then I suggest you to take a look at Java Generics and Collection by Maurice Naftalin and Philip Wadler, one of the best book to learn Java Collections.
Read more »

No comments:

Post a Comment