![]() |
VOOZH | about |
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.
[10, 20, 30] The element at index 2 is 30
get(int index)
If we try to access an index that is out of range i.e., index < 0 or index >= size(), an IndexOutOfBoundsExceptionwill be thrown.
Example 2: Here, we will demonstrate the error when attempting to access an index that is out of range.
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(...