如何使用 Java ArrayList? [英] How to work with 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屋!