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中获取列表的子列表?的详细内容。