嗨,我有以下代码结构

    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循环中要迭代的集合中删除。

09-26 20:36