views:

39

answers:

4

Hi 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 around 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.

A: 

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible

giri
+3  A: 

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()
}
Gerco Dries
Keep in mind that this method can by quite slow for ArrayLists, though it will probably be slightly faster with some other methods due to not needing to "lookup" the items to be removed (e.g. LinkedList and Sets).
deterb
+4  A: 

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);
Sanjay Manohar
Two things. You should use ArrayList instead of a Vector (you don't need the synchronization Vector provides).Also, note that this method is slightly better/worse for different collection implementations. ArrayList is one of them, as if you're removing a bunch of items it can repack them more in one operation rather than every time an item is removed (O(n) rather than O(n^2)).
deterb
+1  A: 

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().

krock