List get() method in Java with Examples
Last Updated :
29 Nov, 2024
Improve
The get() method of List interface in Java is used to get the element present in this list at a given specific index.
Example:
// Java Program to demonstrate List
// get() Method
import java.util.*;
class Main
{
public static void main (String[] args)
{
// Create a List
List<Integer> a=new ArrayList<Integer>();
// Adding Elements in List
a.add(10);
a.add(20);
a.add(30);
// Index
int i = 2;
// Element at Index
int ele = a.get(i);
System.out.println("Element at index " + i
+ " : " + ele);
}
}
Output
Element at index 2 : 30
Syntax of Method
E get(int index)
Where, E is the type of element maintained by this List container.
Parameter : This method accepts a single parameter index of type integer which represents the index of the element in this list which is to be returned.
Return Value: It returns the element at the specified index in the given list.
Errors and exception : This method throws an IndexOutOfBoundsException if the index is out of range (index=size()).
Example of List get() Method
Below programs illustrate the get() method:
Program 1 :
// Java code to demonstrate the working of
// get() method in List
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
// Creating an Empty Integer List
List<Integer> l = new ArrayList<Integer>(4);
// Using add() to initialize values
// [10, 20, 30, 40]
l.add(10);
l.add(20);
l.add(30);
l.add(40);
System.out.println("List: " + l);
// Element at index 2
int ele = l.get(2);
System.out.println("The element at index 2 is " + ele);
}
}
Output
List: [10, 20, 30, 40] The element at index 2 is 30
Program 2 : Program to demonstrate the error.
// Java code to demonstrate the error of
// get() method in List
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Creating an Empty Integer List
List<Integer> l = new ArrayList<Integer>(4);
// Using add() to initialize values
// [10, 20, 30, 40]
l.add(10);
l.add(20);
l.add(30);
l.add(40);
try
{
// Trying to access element at index 8
// which will throw an Exception
int ele = l.get(8);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output
java.lang.IndexOutOfBoundsException: Index: 8, Size: 4
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#get(int)