复制 ArrayList 的前半部分 [英] Copying the first half of an ArrayList

查看:35
本文介绍了复制 ArrayList 的前半部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 ArrayListal,我想将其元素的前半部分复制到另一个 ArrayList;上半部.(如果 al 有奇数个元素,firstHalf 应该多一个元素.)但是,下面的代码抛出一个 IndexOutOfBoundsException,并说 Index: 0,大小:0,虽然我不确定这会有什么问题,因为 ArrayLists 的索引从 0 开始.另外,我知道 .arraycopy,但我想以这种方式使用 for 循环.

There is an ArrayList<Integer> al, and I want to copy the first half of its elements into another ArrayList<Integer> firstHalf. (If al has an odd number of elements, firstHalf should have one more element.) However, the following code throws an IndexOutOfBoundsException, and says Index: 0, Size: 0, though I'm not sure how that would be a problem, since the indices of ArrayLists start at 0. Also, I am aware of .arraycopy, but I would like to do it this way, with for-loops.

 int x = al.size()/2 + (al.size()%2) - 1;
 for(int i = 0; i < x; i++){
    firstHalf.set(i, al.get(i));
 }

推荐答案

你应该使用 add 而不是 set:

You should use add instead of set:

int x = al.size()/2 + (al.size()%2) - 1;
for(int i = 0; i < x; i++){
    firstHalf.add(al.get(i));
 }

最好使用 列表#subList

这篇关于复制 ArrayList 的前半部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆