ArrayList get() – Get Element at Index

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 from the ArrayList.

ArrayList<String> places = new ArrayList<String>(Arrays.asList("a", "b", "c", "d", "e", "f"));

String firstElement = list.get(0);    //a
String sixthElement = list.get(5);    //f

1. ArrayList get() Method

The 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 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.

ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles", "dough"));

String firstName = list.get(0);         //alex
String secondName = list.get(1);        //brian

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode