Reputation: 17
I have a problem with ConcurrentModificationException
.
I have an ArrayList
of Complex
class that I defined. I added two Complex
es, 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
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
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