在Java中,最简单、最标准、或者最高效的方法是将一个List分成两个子List。原始的List可以进行修改,无需进行复制。方法签名可能如下:
public void split(List<T> original, List<T> firstHalf, List<T> secondHalf);
/** 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
,但立即复制结果)。