复制ArrayList的前半部分 [英] Copying the first half of an ArrayList
问题描述
有一个ArrayList<Integer> al
,我想将其元素的前半部分复制到另一个ArrayList<Integer> firstHalf
中. (如果al的元素数量为奇数,则firstHalf
应该再有一个元素.)但是,以下代码抛出一个IndexOutOfBoundsException
并说Index: 0, Size: 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
:
int x = al.size()/2 + (al.size()%2) - 1;
for(int i = 0; i < x; i++){
firstHalf.add(al.get(i));
}
最好使用 List#subList
这篇关于复制ArrayList的前半部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!