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


List介面擴充套件了Collection,並聲明瞭儲存元素序列的集合的行為。List的使用者可以精確地控制要在List中插入元素的位置。這些元素可以透過其索引訪問,並且可以搜尋。ArrayList是List介面最流行的實現。

List介面的subList()方法可以用來獲取List的子列表。它需要起始和結束索引。此子列表包含與原始列表中相同的物件,對子列表的更改也會反映在原始列表中。在本文中,我們將討論subList()方法以及相關的示例。

語法

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<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
      System.out.println("List: " + list);

      // Get the subList
      List<String> subList = list.subList(2, 4);

      System.out.println("SubList(2,4): " + subList);
   }
}

輸出

這將產生以下結果:

List: [a, b, c, d, e]
SubList(2,4): [c, d]

示例 2

以下示例顯示使用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<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));

      System.out.println("List: " + list);

      // Get the subList
      List<String> subList = list.subList(2, 4);
      System.out.println("SubList(2,4): " + subList);

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

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

輸出

這將產生以下結果:

List: [a, b, c, d, e]
SubList(2,4): [c, d]
SubList: []
List: [a, b, e]

更新於:2022年5月26日

7K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.