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);
}
}
|
Output
List: [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)
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
11 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...