繁体   English   中英

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

[英]concurrent modification exception for set iterator

嗨,我有以下代码结构

    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();

somesetst指向同一集合。 因此,实际上您是从第一个方法的for-each循环中迭代的集合中删除。

除非需要将某些东西从s传递给someotherclassfunction(),否则不需要外部for循环。 因此更改以下内容;

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

someotherclassfunction();

应该摆脱ConcurrentModificationException。

暂无
暂无

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

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