如何在Java中获取List的第一个元素?

如何在Java中获取List的第一个元素?

List 接口扩展了 Collection 接口。它是一个存储元素序列的集合。 ArrayList 是 List 接口最流行的实现。列表的用户可以非常精确地控制将元素插入到列表中的位置。这些元素可通过其索引访问并且可搜索。

List 接口提供 get() 方法来获取特定索引处的元素。可以指定index为0来获取List的第一个元素。在本文中,我们将通过多个示例探索 get() 方法的用法。

语法

E get(int index)登录后复制

参数

  • index - 元素的索引返回。

返回

指定位置的元素。

抛出

  • IndexOutOfBoundsException - 如果索引超出范围(index = size())

示例 1

以下示例展示了如何从列表中获取第一个元素。

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 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)); } }登录后复制