集合迭代器的并发修改异常



Hi我有以下代码结构

    Private Set<String> someset = null; //a class variable
    someclassfunction() {
       Set<String> st = mapA.keyset();
       someset = mapA.keyset();
       for (String s: st) { //this is where now the exception occurs
            someotherclassfunction();
       }
    }
    someotherclassfunction() {
       Iterator<String> it = someset.iterator();
       while (it.hasNext()) {
           String key = it.next();
           if (somecondition) {
               it.remove();
           //Earlier I did, someset.remove(key), this threw concurrent
           //modification exception at this point. So I found on stack 
           //overflow that we need to use iterator to remove
           }
       }
    }

但现在,在每个循环的调用函数上都会出现相同的异常。为什么?我不是在修改st集,而是在修改someset(类变量)。请帮忙。

使用此代码:

Set<String> st = mapA.keyset();
someset = mapA.keyset();

CCD_ 1和CCD_ 2都指向同一集合。因此,您实际上是在从第一个方法的for-each循环中迭代的集合中移除。

您不需要外部for循环,除非您需要从s向someotherclassfunction()传递一些东西。因此,改变以下内容;

for (String s: st) { //this is where now the exception occurs
      someotherclassfunction();
}

someotherclassfunction();

应该清除ConcurrentModificationException。

最新更新