如何在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]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP