Java 如何获取List的子列表

Java 如何获取List的子列表

List接口扩展了Collection接口,并声明了一个存储元素序列的集合的行为。列表的用户对于要插入列表中的元素具有非常精确的控制。这些元素可以通过它们的索引进行访问,也可以进行搜索。ArrayList是List接口最常用的实现。

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

语法

List<E> subList(int fromIndex, int 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]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程