关于在List中删除元素引起ConcurrentModificationException的一些解决方法
For-each循环使用一些内部迭代器,这些迭代器会检查集合修改并引发ConcurrentModificationException异常
解决方法一:使用显示迭代器
Iterator<String> iter = myArrayList.iterator();
while (iter.hasNext())
{
String str = iter.next();
if (someCondition)
iter.remove();
}
Iterator.remove()是在迭代过程中修改集合的唯一安全方法。如果在进行迭代时以任何其他方式修改基础集合,则行为很有可能出错
解决方法二:使用索引遍历集合
for(int i = 0;i<list.size();i++)
{
type curElement = list.get(i);
if(sonCondition)
list.remove(curElement);
}
本文探讨了在Java中从List中删除元素时遇到的ConcurrentModificationException异常,并提供了两种有效的解决方案:使用显示迭代器的Iterator.remove()方法和通过索引遍历集合进行元素删除。
6492

被折叠的 条评论
为什么被折叠?



