Java 集合迭代器的并发修改异常
嗨,我有以下代码结构Java 集合迭代器的并发修改异常,java,exception,collections,concurrentmodification,Java,Exception,Collections,Concurrentmodification,嗨,我有以下代码结构 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
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();
someset和st都指向同一个集合。因此,在第一个方法中,实际上是从for each循环中迭代的集合中删除。除非需要从s向someotherclassfunction传递某些内容,否则不需要外部for循环。 因此,改变下面的内容
for (String s: st) { //this is where now the exception occurs
someotherclassfunction();
}
到
应该消除ConcurrentModificationException。那么如何修复它呢?我需要一个参考副本someset将被修改,但不是原来的副本st@ArnavSengupta您需要创建mapA.keySet.So的副本,以便设置anotherSet=mapA.keySet,然后someset=anotherSet修复它?您需要设置anotherSet=new HashSetmapA.keySet;另一组也是一样。@RohitJain不是线程保存,因为复制构造函数操作不是原子的,它不幸地在键集上迭代,当在复制时更改了键集时,您仍然会得到并发修改。我需要为st中的每个s调用它。Rohit上面回答的确实是正确的。无论如何谢谢你!
someotherclassfunction();