This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
                                
                                    (24个答案)
                                
                        
                4年前关闭。
            
        

为什么我收到此例外?

我是java和stackoverflow的新手

ArrayList<A> a = new ArrayList<A>();
ArrayList<B> b = new ArrayList<B>();

a.add(new A("A"));
a.add(new A("B"));
a.add(new A("C"));

b.add(new B(new A("A"), "a"));
b.add(new B(new A("B"), "b"));
b.add(new B(new A("C"), "c"));

System.out.println(a);
System.out.println(b);

bIterator = b.iterator();
while(bIterator.hasNext()) {
    b.add(new B(bIterator.next(), "a"));
}


错误

Exception in thread "main" java.util.ConcurrentModificationException

最佳答案

之所以会出现此异常,是因为您遍历了一个列表并同时对其进行了修改。

关于java - 为什么这段代码给异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31452748/

10-12 00:39
查看更多