请尝试将项添加到arrayList,如下例所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但它引发了一个例外
java.util.ConcurrentModificationException
Run Code Online (Sandbox Code Playgroud)
您能否建议我如何添加这样的项目或正确使用哪种列表(容器)?
使用常规for循环.增强的for循环不允许您在迭代时修改列表(添加/删除):
for(int i = 0; i < list.size(); i++){
int currentNumber = list.get(i);
if((currentNumber % 2) == 0){
list.add(currentNumber * currentNumber);
}
}
Run Code Online (Sandbox Code Playgroud)
正如@MartinWoolstenhulme所提到的,这个循环不会结束.我们根据数组的大小进行迭代,但由于我们在循环遍历时添加到列表中,因此它将继续增大并且永远不会结束.
要避免这种情况,请使用其他列表.通过这种策略,您不再添加到循环播放的列表中.由于您不再修改它(添加它),您可以使用增强的for循环:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用Integer而不是int循环的原因是避免对象和基元之间的自动装箱和拆箱.
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |