如何使用 Java 获取 ArrayList 的子列表?

javaobject oriented programmingprogramming更新于 2025/2/4 18:20:17

List 接口是一个集合,它存储一系列元素。ArrayList 是 List 接口最流行的实现。列表为用户提供了对在列表中插入元素位置的相当精确的控制。这些元素可通过其索引访问并可搜索。ArrayList 是 List 接口最常见的实现。

Java List 提供了一种方法 subList(),该方法根据提供的开始和结束索引返回列表的一部分。在本文中,我们将看到如何使用 subList() 方法从 ArrayList 获取子列表。

语法

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

注释

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

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

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

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

参数

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

  • toIndex - 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<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
      System.out.println("List: " + list);

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

以下示例显示了使用列表中的 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);

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

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

      // 原始列表也会受到影响。
      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]

相关文章


有用资源