首頁  >  文章  >  Java  >  如何在Java中取得List的第一個元素?

如何在Java中取得List的第一個元素?

王林
王林轉載
2023-09-07 18:21:04958瀏覽

如何在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<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.com。如有侵權,請聯絡admin@php.cn刪除