Learn how to get the element from an ArrayList. We will be using ArrayList.get() method to get the object at the specified index of the arraylist.
1. ArrayList get() method
ArrayList.get(int index) method returns the element at the specified position 'index'
in the list.
1.1. get() Syntax
public Object get( int index );
1.2. get() Parameter
index
– index of the element to return. A valid index will always be between 0 (inclusive) to the size of ArrayList (exclusive).
For example, if ArrayList holds 10 objects than a valid argument index will be between 0 to 9 (both inclusive).
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)
1.3. get() Return Value
The get()
method returns the reference of the object present at the specified index.
2. ArrayList get() Example – Get value at index in ArrayList
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.
Note – Please note that arraylist index starts from 0.
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 !!
Read More: