[英]concurrent modification exception for set iterator
Hi I have the following code structure 嗨,我有以下代码结构
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
}
}
}
But now the same exception occurs on the calling function for each loop. 但是现在,每个循环的调用函数都发生相同的异常。 Why is that?
这是为什么? I am not modifying the st set, I am modifying the someset (class variable).
我不是在修改st集,而是在修改someset(类变量)。 Please help.
请帮忙。
With this code: 使用此代码:
Set<String> st = mapA.keyset();
someset = mapA.keyset();
Both someset
and st
point to the same set. someset
和st
指向同一集合。 So you're actually removing from the set you're iterating upon in the for-each
loop in your first method. 因此,实际上您是从第一个方法的
for-each
循环中迭代的集合中删除。
You don't need the outer for loop unless you need to pass something to the someotherclassfunction() from s. 除非需要将某些东西从s传递给someotherclassfunction(),否则不需要外部for循环。 So changing the below;
因此更改以下内容;
for (String s: st) { //this is where now the exception occurs
someotherclassfunction();
}
to 至
someotherclassfunction();
should get rid of the ConcurrentModificationException. 应该摆脱ConcurrentModificationException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.