Java list get()方法及实例
Java中List接口的 get() 方法用于获取该列表中以特定索引存在的元素。
语法:
E get(int index)
Where, E is the type of element maintained
by this List container.
参数: 该方法接受一个整数类型的参数index,代表这个列表中要返回的元素的索引。
返回值 :它返回给定列表中指定索引的元素。
错误和异常: 如果索引超出范围(index=size()),该方法会抛出一个 IndexOutOfBoundsException 。
下面的程序说明了get()方法。
程序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> arr = new ArrayList<Integer>(4);
// using add() to initialize values
// [10, 20, 30, 40]
arr.add(10);
arr.add(20);
arr.add(30);
arr.add(40);
System.out.println("List: " + arr);
// element at index 2
int element = arr.get(2);
System.out.println("The element at index 2 is " + element);
}
}
输出:
List: [10, 20, 30, 40]
The element at index 2 is 30
程序2 :演示错误的程序。
// Java code to demonstrate the error of
// get() method in List
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating an Empty Integer List
List<Integer> arr = new ArrayList<Integer>(4);
// using add() to initialize values
// [10, 20, 30, 40]
arr.add(10);
arr.add(20);
arr.add(30);
arr.add(40);
try {
// Trying to access element at index 8
// which will throw an Exception
int element = arr.get(8);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.IndexOutOfBoundsException: Index: 8, Size: 4
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/List.html#get(int)