简体   繁体   English

ArrayList的并发修改异常

[英]Concurrent Modification Exception with ArrayList

I have a problem with ConcurrentModificationException . 我对ConcurrentModificationException有问题。

I have an ArrayList of Complex class that I defined. 我有一个定义的Complex类的ArrayList I added two Complex es, and try to do a for each loop but I get the ConcurrentModificationException . 我添加了两个Complex es,并尝试为每个循环执行a 但是得到了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. 我需要那些初始点(1,0) (-1,0)来计算,我将在以后需要点。

        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(); 如果您要移动dots.clear(); and temp.clear() outside iterations; 和temp.clear()在迭代之外; 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). 除非迭代器本身具有在迭代器本身上定义的语义( remove方法),否则大多数迭代器实现均不允许修改基础结构。

So, in all the sections of the code where you are clearing the structure while iterating over it, you will get a ConcurrentModificationException . 因此,在遍历结构的同时清除结构的代码的所有部分中,您将获得ConcurrentModificationException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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