ArrayList get(index) Method in Java with Examples
The get() method of ArrayList in Java is used to get the element of a specified index within the list.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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.
List: [10, 20, 30, 40] the element at index 2 is 30
Example 2: Program to demonstrate the error
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)