Java:将一个列表拆分为两个子列表?

标签 java list

在 Java 中将 List 拆分为两个子 List 的最简单、最标准和/或最有效的方法是什么?改变原始列表是可以的,所以不需要复制。方法签名可以是

/** Split a list into two sublists. The original list will be modified to
 * have size i and will contain exactly the same elements at indices 0 
 * through i-1 as it had originally; the returned list will have size 
 * len-i (where len is the size of the original list before the call) 
 * and will have the same elements at indices 0 through len-(i+1) as 
 * the original list had at indices i through len-1.
 */
<T> List<T> split(List<T> list, int i);

[EDIT] List.subList 返回原始列表的 View ,如果原始列表被修改,则该 View 无效。所以 split 不能使用 subList 除非它也免除了原始引用(或者,如 Marc Novakowski 的回答,使用 subList 但立即复制结果)。

最佳答案

快速半伪代码:

List sub=one.subList(...);
List two=new XxxList(sub);
sub.clear(); // since sub is backed by one, this removes all sub-list items from one

它使用标准的 List 实现方法,避免了所有的循环运行。 clear() 方法还将对大多数列表使用内部 removeRange() 并且效率更高。

关于Java:将一个列表拆分为两个子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/379551/

相关文章:

python - 删除列表中重复项之间的所有实例,Python

python - 一种在 Python 中连接字符串中的字符列表的优雅方法

java - 我无法理解 java.sql.date 的文档

java - 为什么整数类缓存值在 -128 到 127 范围内?

java - Java 中通过键连接字符串值的最方便的习惯用法

Java Persistence 与 self 的多对多关系

java - 编写一个由文本字段和按钮组成的自定义 JTable 单元格

list - 测试列表是否代表一个没有重复的集合的过程

c++ - 如何调用列表中对象的函数?

r - 在列表中查找包含 R 中矢量值的对象