Collections

Java ArrayList get first and last element example

Java ArrayList get first and last element example shows how to get first and last element of ArrayList in Java. Example also shows how to check size of ArrayList before getting first and last element to avoid IndexOutOfBoundException.

How to get first and last element of ArrayList in Java?

ArrayList is index based data structure. That means elements of an ArrayList can be accessed using index. Please also note that index of ArrayList starts from zero, so first element of ArrayList is located at index 0 (not 1). Similarly, last element of ArrayList is located at total number of elements – 1 index.

You can get total number of elements of ArrayList using size method.

This method returns total number of elements stored in the ArrayList.

Example

Output

Please note that get method of ArrayList throws IndexOutOfBoundException if index is less than zero or greater than or equal to ArrayList size. For example,

Make sure to always check the size of ArrayList before getting any element using get method.

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.