您好,欢迎访问一九零五行业门户网

如何在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的第一个元素?的详细内容。
其它类似信息

推荐信息