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?