如何使用Java ArrayList? [英] How to work with Java ArrayList?

查看:57
本文介绍了如何使用Java ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请,我尝试将项目添加到arrayList中,如下例所示:

Please, I try to add item to arrayList like example below:

ArrayList<Integer> list = new ArrayList<>();

list.add(2);
list.add(5);
list.add(7);

for(int i : list ){
    if((i%2) == 0){
         list.add(i*i);
    }
}

但是会引发异常

java.util.ConcurrentModificationException

请问我如何添加这样的项目或正确使用哪种列表(容器)?

Could you please advice how can I add item like this or what kind of list (container) is to be used correctly?

推荐答案

使用常规的for循环.增强的for循环不允许您在遍历列表时修改列表(添加/删除):

Use a regular for loop. Enhanced for loops do not allow you to modify the list (add/remove) while iterating over it:

for(int i = 0; i < list.size(); i++){
    int currentNumber = list.get(i);

    if((currentNumber % 2) == 0){
        list.add(currentNumber * currentNumber);
    }
}


正如@MartinWoolstenhulme所提到的,此循环不会结束.我们根据数组的大小进行迭代,但是由于我们在循环访问数组时将其添加到列表中,因此数组的大小将继续增长,并且永无止境.


As @MartinWoolstenhulme mentioned, this loop will not end. We iterate based on the size of the array, but since we add to the list while looping through it, it'll continue to grow in size and never end.

为避免这种情况,请使用其他列表.通过这种策略,您不再需要添加到正在循环浏览的列表中.由于不再需要修改(添加),因此可以使用增强的for循环:

To avoid this, use another list. With this tactic, you no longer add to the list you are looping through. Since you are no longer modifying it (adding to it), you can use an enhanced for loop:

List<Integer> firstList = new ArrayList<>();
//add numbers to firstList

List<Integer> secondList = new ArrayList<>();

for(Integer i : firstList) {
    if((i % 2) == 0) {
        secondList.add(i * i);
     }
}

我在循环中使用Integer而不是int的原因是为了避免在对象和基元之间自动装箱和拆箱.

The reason I use Integer instead of int for the loop is to avoid auto-boxing and unboxing between object and primitive.

这篇关于如何使用Java ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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