简体   繁体   中英

Concurrent Modification Exception with ArrayList

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM