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

查看:203
本文介绍了复制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屋!

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