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

Java中将列表拆分为两个子列表的最简单,最标准和/或最有效的方法是什么?可以更改原始列表,因此无需复制。方法签名可以是

/** 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返回原始列表上的视图,如果修改了原始视图,该视图将无效。因此,除非它也放弃了原始参考文献,否则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:将一个列表分为两个子列表? 的全部内容, 来源链接: utcz.com/qa/400188.html

回到顶部