Java的:异常时,在for-each循环删除列表里面记录 [英] Java: Exception when remove a record inside a List in a for-each loop
问题描述
我有一个名单,我想通过列表循环和一定条件下删除一些备案基地。下面是我做的。
公共无效美孚(列表<酒吧GT; recordList){
对于(酒吧酒吧:recordList){
如果(bar.someCondition()){
recordList.remove(巴);
}
}
}
这code产生异常。如果我使用iterator然后正常工作
公共无效美孚(列表<酒吧GT; recordList){
迭代器<酒吧GT; ITER = recordList.iterator();
而(iter.hasNext()){
酒吧酒吧= iter.next();
如果(bar.someCondition()){
iter.remove();
}
}
}
我想我的问题:
-
为什么code的第一块不起作用?
-
如何让我的第一块code的工作?
-
它不工作,因为你正在修改的集合,而在它迭代。这意味着你正在改变其状态,并在同一时间阅读。这激起了收藏的胆意外行为,并prevent数据损坏,则抛出异常。
-
您不能使其工作。你必须使用迭代器。
I have a List, and I want to loop through that List and remove some record base on some condition. Here is what I do
public void foo(List<Bar> recordList){
for(Bar bar : recordList){
if(bar.someCondition()){
recordList.remove(bar);
}
}
}
This code generate exception. If I use Iterator then it works fine
public void foo(List<Bar> recordList){
Iterator<Bar> iter = recordList.iterator();
while(iter.hasNext()){
Bar bar = iter.next();
if(bar.someCondition()){
iter.remove();
}
}
}
I guess my question:
Why the first piece of code does not work?
How do I make the first piece of code work?
It doesn't work because you are modifying a collection WHILE iterating on it. It means you are changing its state and reading it at the same time. This provokes unexpected behaviours in the inners of the collection, and to prevent data corruption, an exception is thrown.
You don't make it work. You have to use iterators.
这篇关于Java的:异常时,在for-each循环删除列表里面记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!