在 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/