Java:将List拆分为两个子列表? [英] Java: split a List into two sub-Lists?
问题描述
将List拆分为Java中的两个子列表的最简单,最标准和/或最有效的方法是什么?改变原始列表是可以的,因此不需要复制。方法签名可以是
What's the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It's OK to mutate the original List, so no copying should be necessary. The method signature could be
/** 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);
List.subList
返回在原始列表上查看,如果原始文件被修改则该列表无效。所以 split
不能使用 subList
,除非它也免除原始参考(或者,如Marc Novakowski的回答,使用 subList
但立即复制结果。)
List.subList
returns a view on the original list, which becomes invalid if the original is modified. So split
can't use subList
unless it also dispenses with the original reference (or, as in Marc Novakowski's answer, uses subList
but immediately copies the result).
推荐答案
快速半伪代码:
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
中删除所有子列表项目列出实现方法并避免所有在循环中运行。对于大多数列表,clear()方法也将使用内部 removeRange()
,并且效率更高。
That uses standard List implementation methods and avoids all the running around in loops. The clear() method is also going to use the internal removeRange()
for most lists and be much more efficient.
这篇关于Java:将List拆分为两个子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!