Java 如何从List中获取元素
可以使用get()方法从列表中检索元素。
语法
E get(int index)
返回列表中指定位置的元素。
参数
- index - 要返回的元素的索引。
返回值
列表中指定位置的元素。
异常
- IndexOutOfBoundsException - 如果索引超出范围(index < 0 || index >= size())。
此处的索引表示列表中元素E的索引。如果索引超出范围,将抛出IndexOutOfBoundsException异常。
示例
以下是使用get()方法从列表中获取元素的示例:
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
System.out.println("List: " + list);
System.out.println("List(1): " + list.get(1));
try {
System.out.println("List(3): " + list.get(3));
}catch(IndexOutOfBoundsException e) {
System.out.println(e);
}
}
}
输出
这将产生以下结果−
List: [A, B, C]
List(1): B
java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3