![](/img/trans.png)
[英]ConcurrentModificationException when using iterator and iterator.remove()
[英]ConcurrentModificationException in removing element in ArrayList [Using iterator.remove()]
我知道我们不应该在迭代过程中修改ArrayList。
但是我正在使用Iterator遍历列表,并使用iterator.remove()删除元素,但仍然导致ConcurrentModification Exception。
我的程序不是多线程的。
我有很多arraylist [类包含它,并且我正在处理许多对象数组]
for(int i=0;i<obj.length;i++)
{
if(k==i) continue;
it = obj[i].arraylist.iterator();
while(it.hasNext()){
value = it.next();
if(condn) {
it.remove();
obj[k].arraylist.add(value);
//k and i are not same
}
}
}
“请注意,Iterator.remove是在迭代期间修改集合的唯一安全方法;如果在进行迭代时以其他任何方式修改基础集合,则行为未指定。”
您可以删除对象,但不能在迭代过程中添加新对象,这就是为什么要获取ConcurrentModificationException的原因。
http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
编辑:您还可以检查:
if(k==i || obj[i].arraylist == obj[k].arraylist) continue;
您只能使用it
变量在迭代过程中修改List。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.