我正在阅读关于并发修改异常的文章,并注意到在使用增强的for循环抛出并发修改异常的情况下删除元素的情况下,而普通的for循环不会抛出并发修改异常。
import java.util.ArrayList;
import java.util.List;
public class ConcurrentModificationExceptionExample {
public static void main(String args[]) {
List<String> myList = new ArrayList<String>();
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("4");
myList.add("5");
// enhanced for loop
/* for(String s:myList){
if(s.equals("1")){
myList.remove("1");
}
}*/
// normal for loop
for(int i = 0; i<myList.size(); i++){
if(myList.get(i).equals("1")){
myList.remove("1");
}
}
System.out.println(myList);
}
}for testing //enhanced for循环可以取消注释
发布于 2019-01-10 13:33:19
这是因为在您的“普通for循环”代码中没有涉及到Iterator。相反,您可以使用get单独访问这些元素。
发布于 2019-01-10 13:33:59
循环表示法
for (String s: myList) {
...
}在后台创建迭代器对象。迭代器跟踪集合的修改。当你不使用迭代器进行修改时,你会得到一个ConcurrentModificationException。
在使用时
for (int i = 0; i < myList.size(); i++) {
...
},并使用
myList.get(i)没有创建迭代器,因此没有抛出异常的机会。
https://stackoverflow.com/questions/54122420
复制相似问题