Java - ConcurrentModificationException

Jak*_*r00 -1 java concurrentmodification

几乎每次调用时,下面的代码都会引发ConcurrentModificationException.第二段代码不会抛出异常,但它不是我需要的正确逻辑.如果对象是一个实例EditorFrame,我需要调用一个自定义处理策略,这就是close()方法.但是,如果它只是一个我希望它调用的基本帧dispose().

我环顾了这个网站并遵循了一些指示,但我找不到任何指示.

抛出异常的代码:

synchronized (frameList) {
    for (Iterator<JFrame> it = frameList.iterator(); it.hasNext();) {
        JFrame frame = it.next();
        if (frame instanceof EditorFrame) ((EditorFrame) frame).close();
        else frame.dispose();
        it.remove();
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码有效,但这不是我想要的:

synchronized (frameList) {
    for (Iterator<JFrame> it = frameList.iterator(); it.hasNext();) {
        JFrame frame = it.next();
        frame.dispose();
        it.remove();
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Nit*_*man 6

无法确切地了解导致ConcurrentModificationException的原因.你还在删除每个对象frameList

完成迭代列表后,为什么不明确清除列表.

synchronized (frameList) {
    for (JFrame frame : frameList) {
        if (frame instanceof EditorFrame) ((EditorFrame) frame).close();
        else frame.dispose();
    }
    frameList.clear();
}
Run Code Online (Sandbox Code Playgroud)