Java ArrayList subList()详解

培训教学 潘老师 7个月前 (09-27) 181 ℃ (0) 扫码查看

学习如何获取现有 ArrayList 的子列表。我们将使用 ArrayList.subList() 方法来获取 ArrayList 对象的子列表。

1.ArrayList.subList() API

subList() 方法返回位于指定 fromIndex(包含)和 toIndex(不包括)之间的列表部分的视图。

public List<E> subList(int fromIndex, int toIndex)

该方法的参数如下:

  • fromIndex – 现有 ArrayList 中的起始索引。它是包含在内的。
  • toIndex – 现有 ArrayList 中的最后一个索引。它是不包含在内的。

请注意,对子列表中的对象进行的任何更改也会反映在原始 ArrayList 上。

2.在指定索引之间获取子列表

以下 Java 程序从现有子列表获取一个子列表。我们将从索引 2 到 6 获取子列表。

请注意,ArrayList 的索引从 0 开始。

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
ArrayList<Integer> sublist = list.subList(2, 6);
System.out.println(sublist);

程序输出:

[2, 3, 4, 5]

3.从指定索引到列表末尾获取子列表

如果我们想要从指定索引获取子列表到列表末尾,那么在方法的第二个参数中传递 ArrayList 的长度。

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
System.out.println(list.subList(2, list.size()));

程序输出:

[2, 3, 4, 5, 6, 7, 8, 9]

4.从原始列表中删除子列表

当我们拥有 ArrayList 的子列表视图时,我们也可以使用这个子列表从 ArrayList 中移除多个项目,因为更改会同时反映在这两个列表中。

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
list.subList(2, 6).clear();
System.out.println(list);

程序输出:

[0, 1, 6, 7, 8, 9]

以上就是Java ArrayList subList()子列表详解的全部内容。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/teach/9301.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】