我知道我们不应该在迭代期间修改 ArrayList。
但是我使用 Iterator 迭代列表并使用 iterator.remove() 删除元素,但仍然导致 ConcurrentModification 异常。
我的程序不是多线程的。
我有很多数组列表[类包含它,我正在处理许多对象数组]
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
}
}
}
最佳答案
"Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."
您可以在迭代期间删除对象,但不能添加新对象,这就是您收到 ConcurrentModificationException 的原因。
http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
编辑: 您还可以检查:
if(k==i || obj[i].arraylist == obj[k].arraylist) continue;
关于java - 删除 ArrayList 中的元素时出现 ConcurrentModificationException [使用 iterator.remove()],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18629430/