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

javaobject oriented programmingprogramming

List 接口扩展了 Collection,并声明了存储元素序列的集合的行为。列表的用户可以非常精确地控制在 List 中插入元素的位置。这些元素可以通过其索引访问,并且可以搜索。ArrayList 是 List 接口最流行的实现。

List 接口方法 subList() 可用于获取列表的子列表。它需要开始和结束索引。此子列表包含与原始列表相同的对象,对子列表的更改也将反映在原始列表中。在本文中,我们将通过相关示例讨论 subList() 方法。

语法

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

注释

  • 返回此列表在指定的 fromIndex(含)和 toIndex(不含)之间的部分的视图。

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

  • 返回的列表由此列表支持,因此返回列表中的非结构性更改会反映在此列表中,反之亦然。

  • 返回的列表支持此列表支持的所有可选列表操作。

参数

  • fromIndex - subList 的低端点(含)。

  • toIndex - subList 的高端点(不含) subList。

返回

此列表中指定范围的视图。

抛出

  • 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);

      // 获取子列表
      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);

      // 获取子列表
      List<String> subList = list.subList(2, 4);
      System.out.println("SubList(2,4): " + subList);

      // 清除子列表
      subList.clear();
      System.out.println("SubList: " + subList);

      // 原始列表也会受到影响。
      System.out.println("List: " + list);
   }
}

输出

将产生以下结果 −

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

相关文章