Learn to get an element from an ArrayList using its index position. We will be using ArrayList.get() method to get the object at the specified index of the arraylist.
ArrayList<String> list = //List instance String firstElement = list.get(0); String sixthElement = list.get(5);
1. ArrayList get() Method
ArrayList.get(int index)
method returns the element at the specified position 'index'
in the list.
1.1. Syntax
public Object get( int index );
1.2. Method Parameter
index
– index of the element to return. A valid index is always be between 0 (inclusive) to the size of ArrayList (exclusive).
For example, if ArrayList holds 10
objects then a valid argument index will be between 0
to 9
(both inclusive).
1.3. Return Value
The get()
method returns the reference of the object present at the specified index.
1.4. IndexOutOfBoundsException
An invalid index argument will cause IndexOutOfBoundsException
error.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429) at com.howtodoinjava.example.ArrayListExample.main(ArrayListExample.java:12)
2. ArrayList get() Example
Java program for how to get an object from ArrayList by its index location. In this example, we want to get the object stored at index locations 0
and 1
.
import java.util.ArrayList; import java.util.Arrays; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(Arrays .asList("alex", "brian", "charles", "dough")); String firstName = list.get(0); //alex String secondName = list.get(1); //brian System.out.println(firstName); System.out.println(secondName); } }
Program output.
alex brian
Happy Learning !!