從 Java 中的 ArrayList 中檢索元素


使用 ArrayList 類中的 java.util.ArrayList.get() 方法,可以從 Java 中的 ArrayList 中檢索元素。此方法有一個引數,即要返回的元素的索引。

演示此操作的程式如下

示例

 線上演示

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List aList = new ArrayList();
      aList.add("James");
      aList.add("George");
      aList.add("Bruce");
      aList.add("Susan");
      aList.add("Martha");
      System.out.println("The element at index 3 in the ArrayList is: " + aList.get(3));
   }
}

上述程式的輸出如下

The element at index 3 in the ArrayList is: Susan

現在來了解一下上述程式。建立 ArrayList aList。然後,使用 ArrayList.add() 將元素新增到 ArrayList 中。

然後,使用 ArrayList.get() 方法檢索索引 3 處的元素,並顯示此元素。演示此操作的程式碼片段如下

List aList = new ArrayList();
aList.add("James");
aList.add("George");
aList.add("Bruce");
aList.add("Susan");
aList.add("Martha");
System.out.println("The element at index 3 in the ArrayList is: " + aList.get(3));

更新於: 13-9-2023

27K+ 瀏覽量

開始你的 職業

完成課程以獲得認證

開始
廣告