如何在Java中獲取ArrayList的子列表?


List介面是一個集合,它儲存一系列元素。ArrayList是List介面最流行的實現。列表允許使用者精確控制元素在列表中的插入位置。這些元素可以透過索引訪問並進行搜尋。ArrayList是List介面最常見的實現。

Java List提供了一個subList()方法,該方法根據提供的起始和結束索引返回列表的一部分。在本文中,我們將看到如何使用subList()方法從ArrayList中獲取子列表。

語法

List<E> subList(int fromIndex, int toIndex)

註釋

  • 返回此列表中指定fromIndex(包含)和toIndex(不包含)之間部分的檢視。

  • 如果fromIndex和toIndex相等,則返回的列表為空。

  • 返回的列表由此列表支援,因此返回列表中的非結構性更改會反映在此列表中,反之亦然。

  • 返回的列表支援此列表支援的所有可選列表操作。

引數

  • fromIndex - 子列表的低端點(包含)。

  • toIndex - 子列表的高階點(不包含)。

返回值

此列表中指定範圍的檢視。

丟擲異常

  • IndexOutOfBoundsException - 對於非法的端點索引值 (fromIndex < 0 || toIndex > size || fromIndex > toIndex)

示例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(0,1,2,3,4,5,6,7,8,9));
      System.out.println("List: " + list);

      // Get the subList
      List<Integer> subList = list.subList(3, 9);
      System.out.println("SubList: " + subList);
   }
}

輸出

這將產生以下結果:

List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
SubList: [3, 4, 5, 6, 7, 8]

示例2

以下示例顯示了使用List的subList()方法建立子列表時的副作用。

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(0,1,2,3,4,5,6,7,8,9));
      System.out.println("List: " + list);

      // Get the subList
      List<Integer> subList = list.subList(3, 9);
      System.out.println("SubList: " + subList);

      // Clear the sublist
      subList.clear();
      System.out.println("SubList: " + subList);

      // Original list is also impacted.
      System.out.println("List: " + list);
   }
}

輸出

這將產生以下結果:

List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
SubList: [3, 4, 5, 6, 7, 8]
SubList: []
List: [0, 1, 2, 9]

更新於:2022年5月26日

2K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告