Jan 30

The general cause of a ConcurrentModificationException is from trying to remove an instance from a collection that is being iterated over as in the following example.


Iterator i = mylist.iterator();
while (i.hasNext())
{
   Object o = i.next();
   if (something)
   {
       // following line will throw ConcurrentModificationException
       mylist.remove(o);
   }
}

The correct way is to instead use the Iterator’s remove() method as shown in the following snippet:


Iterator i = mylist.iterator();
while (i.hasNext())
{
   Object o = i.next();
   if (something)
   {
       i.remove();
   }
}

written by objects \\ tags: , ,


6 Responses to “How to fix ConcurrentModificationException?”

  1. Sergi Says:

    Thank you very much! This solved a problem I had that was driving me crazy.

  2. Raymond Says:

    Thank you, you just save my day !!!

  3. Mike Says:

    Like the others, thanks, you’ve saved me a headache!

  4. Nick Says:

    Thanks for the explanation!!!
    In my case I decided to do clone(), so to avoid this, because my program runs in two threads.

  5. devi Says:

    Thanks a lot…

  6. Robby Says:

    Thx, worked like a charm 🙂

Leave a Reply

You must be logged in to post a comment.