
List 接口扩展了 Collection 并声明了存储元素序列的集合的行为。列表的用户可以非常精确地控制将元素插入到列表中的位置。这些元素可通过其索引访问并且可搜索。 ArrayList是List接口最流行的实现。
List接口方法subList()可用于获取列表的子列表。它需要开始和结束索引。该子列表包含与原始列表中相同的对象,并且对子列表的更改也将反映在原始列表中。在本文中,我们将通过相关示例讨论 subList() 方法。
List<E> subList(int fromIndex, int toIndex)
返回此列表中指定 fromIndex(包括)和 toIndex(不包括)之间部分的视图。
如果 fromIndex 和 toIndex 相等,则返回的列表为空。
立即学习“Java免费学习笔记(深入)”;
返回的列表由此列表支持,因此返回列表中的非结构性更改会反映在此列表中,反之亦然。
返回的列表支持此列表支持的所有可选列表操作。
fromIndex - 子列表的低端点(包括)。
toIndex - 子列表的高端点(不包括)。
此列表中指定范围的视图。
IndexOutOfBoundsException - 对于非法的端点索引值(fromIndex < 0 || toIndex > size || fromIndex > toIndex)
以下是从列表中获取子列表的示例:
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]
以下示例显示使用 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]
以上就是如何在Java中获取列表的子列表?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号