The get() method of ArrayList in Java is used to get the element of a specified index within the list.
Syntax:
get(index)
Parameter: Index of the elements to be returned. It is of data-type int.
Return Type: The element at the specified index in the given list.
Exception: It throws IndexOutOfBoundsException if the index is out of range (index=size())
Note: Time Complexity: ArrayList is one of the List implementations built a top an array. Hence, get(index) is always a constant time O(1) operation.
Example:
Java
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>( 4 );
arr.add( 10 );
arr.add( 20 );
arr.add( 30 );
arr.add( 40 );
System.out.println( "List: " + arr);
int element = arr.get( 2 );
System.out.println( "the element at index 2 is "
+ element);
}
}
|
OutputList: [10, 20, 30, 40]
the element at index 2 is 30
Example 2: Program to demonstrate the error
Java
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>( 4 );
arr.add( 10 );
arr.add( 20 );
arr.add( 30 );
arr.add( 40 );
int element = arr.get( 5 );
System.out.println( "the element at index 2 is "
+ element);
}
}
|
Output :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 4
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
at GFG.main(GFG.java:22)