user1965206
user1965206

Reputation: 17

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();
        }

Upvotes: 0

Views: 370

Answers (2)

asermax
asermax

Reputation: 3123

Most iterators implementations don't allow the underlying structure to be modified unless it's with the defined semantics on the iterator itself (the remove method).

So, in all the sections of the code where you are clearing the structure while iterating over it, you will get a ConcurrentModificationException.

Upvotes: 0

Deepak Singhal
Deepak Singhal

Reputation: 10874

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.

Upvotes: 1

Related Questions