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.
1 |
public int size() |
This method returns the total number of elements stored in the ArrayList.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.javacodeexamples.collections.arraylist; import java.util.ArrayList; public class ArrayListGetFirstLastElementExample { public static void main(String[] args) { //create ArrayList ArrayList<String> aListOS = new ArrayList<String>(); //add elements aListOS.add("Windows"); aListOS.add("Unix"); aListOS.add("Mac OS X"); //print ArrayList System.out.print("ArrayList contains: "); System.out.println(aListOS); /* * To get the first element of ArrayList * use get method with index as 0 */ System.out.print("ArrayList first element: "); System.out.println( aListOS.get(0) ); /* * To get the last element of ArrayList * use get method with index as size - 1 */ System.out.print("ArrayList last element: "); System.out.println( aListOS.get( aListOS.size() - 1 ) ); } } |
Output
1 2 3 |
ArrayList contains: [Windows, Unix, Mac OS X] ArrayList first element: Windows ArrayList last element: Mac OS X |
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,
1 2 3 4 5 6 7 |
ArrayList<String> aListOS = new ArrayList<String>(); System.out.println( aListOS.get(0) ); //throws exception aListOS.add("Windows"); System.out.println( aListOS.get(1) ); //throws exception |
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.
Copy/paste error on line 35,
System.out.print(“ArrayList first element: “);
actually gets the last element.
Hello Barg,
Nice catch. Fixed it.
I really appreciate your effort to point that out.