Java 如何获取List的第一个元素
列表接口继承自集合接口。列表是一种存储元素序列的集合。ArrayList是列表接口最常见的实现方式。列表的用户可以精确控制元素在列表中的插入位置。这些元素可以通过它们的索引进行访问和搜索。
列表接口提供了一个get()方法来获取特定索引处的元素。您可以将索引指定为0来获取列表的第一个元素。本文将通过多个示例探讨get()方法的使用。
语法
E get(int index)
返回指定位置的元素。
参数
- index - 要返回元素的索引。
返回值
指定位置的元素。
异常
- IndexOutOfBoundsException - 如果索引超出范围(index < 0 || index >= size())
示例1
以下是一个示例,展示如何从List中获取第一个元素。
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(4,5,6));
System.out.println("List: " + list);
// First element of the List
System.out.println("First element of the List: " + list.get(0));
}
}
输出
这将产生以下结果−
List: [4, 5, 6]
First element of the List: 4
示例2
下面是一个示例,从列表中获取第一个元素可能会引发异常。
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
System.out.println("List: " + list);
try {
// First element of the List
System.out.println("First element of the List: " + list.get(0));
} catch(Exception e) {
e.printStackTrace();
}
}
}
输出
这将产生以下结果-
List: []
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:659)
at java.util.ArrayList.get(ArrayList.java:435)
at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:11)