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

王林
王林 转载
2023-09-07 18:21:04 222浏览

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

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

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

语法

E get(int index)

返回指定位置的元素。

参数

  • index - 元素的索引返回。

返回

指定位置的元素。

抛出

  • IndexOutOfBoundsException - 如果索引超出范围(index < 0 || 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<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

以下示例中,从 List 中获取第一个元素可能会引发异常。

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)

以上就是如何在Java中获取List的第一个元素?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除