Search code examples
javaarraylistjava.util.concurrentconcurrentmodification

Concurrent Modification Exception with ArrayList


I have a problem with ConcurrentModificationException.

I have an ArrayList of Complex class that I defined. I added two Complexes, and try to do a for each loop but I get the ConcurrentModificationException. However, when I remove that line, I get no error. I need those initial points (1,0), (-1,0) to calculate points that I will need later.

        for (Iterator<Complex> num = dots.iterator(); num.hasNext();) {
            // ConcurrentModificationException
            Complex aComplex = num.next();
            // clone it and clear
            temp.add(new Complex(aComplex));
            dots.clear();
        }

Solution

  • You cannot modify a collection while iterating on it. If you would move dots.clear(); and temp.clear() outside iterations; it will get resolved. If needed you can create a flag whenever these collections need to be cleared; and after iteration is over you can clear them.