ArrayList get(index) Method in Java with Examples
Last Updated : 10 Dec, 2024
Improve
The get(index) method of ArrayList in Java is used to retrieve the element at the specified index within the list.
Example 1: Here, we will use the get() method to retrieve an element at a specific index in an ArrayList of integers.
// Java program to demonstrate the working of
// get() method in ArrayList
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an ArrayList of Integers
ArrayList<Integer> arr = new ArrayList<Integer>(3);
// Adding elements to the ArrayList
arr.add(10);
arr.add(20);
arr.add(30);
System.out.println("" + arr);
// Getting the element at index 2
int e = arr.get(2);
System.out.println("The element at index 2 is " + e);
}
}
Output
[10, 20, 30] The element at index 2 is 30
Syntax of get(index) Method
get(int index)
- Parameter: The index of the element to be returned. It is of data-type int.
- Return Type: The element at the specified index in the given list.
If we try to access an index that is out of range i.e., index < 0 or index >= size(), an IndexOutOfBoundsException will be thrown.
Example 2: Here, we will demonstrate the error when attempting to access an index that is out of range.
// Java program to demonstrate error generated
// while using get() method in ArrayList
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an ArrayList of Integers
ArrayList<Integer> arr = new ArrayList<Integer>(4);
// Adding elements to the ArrayList
arr.add(10);
arr.add(20);
arr.add(30);
arr.add(40);
// Trying to access an element
// at an invalid index
int e = arr.get(5);
// Printing the element at
// index 5 (will throw exception)
System.out.println("The element at index 5 is " + e);
}
}
Output:
Hangup (SIGHUP)
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 4
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:459)
at GFG.main(...