Iteration,concurrentModifcationException in Java
I'm using a enhanced for loop over an ArrayList and wanted to remove some elements that contain a particular value.
When I try to do this I get the above exception. I've had a look aroun开发者_开发技巧d and it seems using a enhanced for loop while modifying the collection is a bad idea. How else would I go about this?
thanks for any help.
You can keep a list of the items to be removed, then call removeAll after the loop has finished.
Vector toRemove=new Vector();
for (Object o: array){
if(remove(o)) toRemove.add(o);
}
array.removeAll(o);
You should get an Iterator for the collection, walk that and call the remove() method on the iterator when you want to remove an element. Please be advised that not all Iterator implementations support remove(), it's an optional method!
for(Iterator it = collection.iterator(); it.hasNext();) {
Object element = it.next();
if(.. should remove element ..)
it.remove()
}
You cannot use the enhanced for loop to do this as you do not have access to the Iterator
being used. You need to use a regular for loop and remove elements of the ArrayList
via Iterator.remove()
.
精彩评论