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 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 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.
Happy Learning !!
Was this post helpful?
Further Reading:
- Arraylist lastIndexOf[] Get last index of element in arraylist in Java
Learn to get last index of element in arraylist in Java using Arraylist.lastIndexOf[] method. It returns the last occurrence of...
- Arraylist indexOf[] Get index of element in arraylist
Learn how to get the index of first occurrence of a element in the ArrayList. We will be using ArrayList.indexOf[]...
- ArrayList add/replace element at specified index in Java
Java program to replace element at specified index of arraylist using ArrayList.add[int index, E element] and ArrayList.set[int index, E element]...