为什么在使用迭代器时会收到ConcurrentModificationException?

时间:2018-12-13 15:00:41

标签: java arrays loops iterator

我正在使用以下代码遍历arraylist,然后方法setAllDancersRest()将编辑我遍历的arraylist。我试图通过使用迭代器来解决此问题,但仍然出现异常。

    for (Iterator<Dance> iterator = allDances.iterator(); iterator.hasNext();) {
        Dance dance = iterator.next();
        if(generated.size()<= 0) {
            generated.add(dance);
        }
        else if(allDancersReady(dance, gap)) {
            generated.add(dance);
            for(Dancer dancer: dance.getPerformers()) {
                dancer.setPerformed();
            }
            setAllDancersRest(dance);
        }
    }

我的错误:

    Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at EliminationGenerator.generateOrder(EliminationGenerator.java:23)
at EliminationGenerator.generateOrder(EliminationGenerator.java:1)
at Model.generateRunningOrder(Model.java:98)
at TUI.getAndProcessUserOption(TUI.java:70)
at TUI.<init>(TUI.java:27)
at testMain.main(testMain.java:11)

allDancersReady()的主体:

private boolean allDancersReady(Dance dance, int givenGap) {
    for(Dancer dancer: dance.getPerformers()) {
        dancer.setGap(givenGap);
        if(!dancer.isReady()) {
            return false;
        }
    }
    return true;
}

setAllDancersRest()的正文:

private void setAllDancersRest(Dance dance) {
    allDances.remove(dance);
    Set<Dancer> dancers = new HashSet<Dancer>();
    for(Dance tempo: allDances) {
        dancers.addAll(tempo.getPerformers());
    }
    dancers.removeAll(dance.getPerformers());
    for(Dancer dancertemp: dancers) {
        dancertemp.notPerformed();
    }

}

0 个答案:

没有答案