0

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();
        }
1
  • Shouldn't dots.clear() and temp.clear() be outside of the corresponding for's? Commented Jan 10, 2013 at 1:38

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.