Skip to content

Java ArrayList get first and last element example

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

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

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

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

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

Example

Output

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

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

This example is a part of the Java ArrayList tutorial.

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

About the author

2 comments

Leave a Reply

Your email address will not be published.