如何在 Java 中獲取 List 的第一個元素?
List 介面擴充套件了 Collection 介面。它是一個儲存元素序列的集合。ArrayList 是 List 介面最流行的實現。List 的使用者可以非常精確地控制在 List 中插入元素的位置。這些元素可以透過它們的索引訪問,並且可以搜尋。
List 介面提供了一個 get() 方法來獲取特定索引處的元素。您可以將索引指定為 0 以獲取 List 的第一個元素。在本文中,我們將透過多個示例探討 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
以下示例中,從 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
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP