如何在Java中获取列表的子列表?
List 接口扩展了 Collection 并声明了存储元素序列的集合的行为。列表的用户可以非常精确地控制将元素插入到列表中的位置。这些元素可通过其索引访问并且可搜索。 ArrayList是List接口最流行的实现。
List接口方法subList()可用于获取列表的子列表。它需要开始和结束索引。该子列表包含与原始列表中相同的对象,并且对子列表的更改也将反映在原始列表中。在本文中,我们将通过相关示例讨论 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]
以上是如何在Java中获取列表的子列表?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处
