普通遍历中删除
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
for(Integer i : arr){
if(i == 2){
arr.remove(i);
}
}
报错
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
at Main.main(Main.java:24)
迭代器遍历中删除
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
Iterator<Integer> iterator = arr.iterator();
while(iterator.hasNext()){
if(iterator.next() == 2){
iterator.remove();
}
}
正常执行
[1, 3, 4, 5]
标签:arr,java,iterator,删除,ArrayList,列表,util,add,Java
From: https://www.cnblogs.com/DCFV/p/18424620