views:

223

answers:

4

what is this exception and how to remove this in my problem i am creating an arraylist of objects, and after checking some condition,i want to remove some objects. but the program is giving this exception ConcurrentModificationException. how to remove this thanks in advance

+1  A: 

You can't modify (meaning adding or removing elements) a collection you are iterating over. The easiest solution is to copy the results you want to keep to a new collection.

Edit: to clarify, you can use the Iterator to remove() elements so you can do:

List<T> list = ...
for (Iterator<T> iter = list.iterator(); iter.hasNext(); ) {
  T obj = iter.next();
  if (obj.someCondition()) {
    iter.remove();
  }
}

But you can't do:

List<T> list = ...
for (Iterator<T> iter = list.iterator(); iter.hasNext(); ) {
  T obj = iter.next();
  if (obj.someCondition()) {
    list.remove(0);
  }
}
cletus
A: 

You probably have an Iterator and try to remove some elements in the Collection. See CurrentModificationException with an Iterator

Rickard von Essen
+3  A: 

You can only modify the collection that you are iterating over by using the Iterator itself (it has a remove method to remove the current element, and ListIterators also have add and set).

 while(it.hasNext()){
   MyObject o = it.next();
   if (aCondition(o))
     it.remove();
 }

If that does not work, you need to make a copy of the collection.

Thilo
A: 

A ConcurrentModificationException usually happens when you try to modify a Collection (like an ArrayList) while you're iterating over it. You haven't posted your code, but if you're removing objects while you're using an iterator for the list, that's your problem. To solve the problem, hold onto references to the objects you want to remove (perhaps in another ArrayList), then iterate over the new ArrayList and remove them from the original list. Something like:

import java.util.ArrayList;

public class TestRemove {
   public static void main(String[] args) {
      ArrayList<String> originalList = new ArrayList<String>();
      originalList.add("foo");
      originalList.add("bar");
      originalList.add("bat");
      originalList.add("baz");
      originalList.add("bar");

      ArrayList<String> removeList = new ArrayList<String>();

      for(String currEntry : originalList) {
         if(currEntry.startsWith("ba")) {
            removeList.add(currEntry);
         }
      }

      for(String removeEntry : removeList) {
         originalList.remove(removeEntry);
      }

     for(String currEntry : originalList) {
        System.out.println(currEntry);
     }
  }

}

If the list is small, you can just copy the items you want to keep to a new list instead.

Rob Heiser