Java, ArrayList and Exception in thread “AWT-EventQueue-0” java.util.ConcurrentModificationException
iterating through an ArrayList. If I use the old fashion way
for (int i = 0; i < list.size(); i++)
{
list.get(i).update();;
}
it runs ok. But with this:
for (Baseitem item : list)
{
item.update();
}
it fails at the first line, inside ArrayList class: Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException yes, outside I do remove items - but certainly not while iterating. How to solve this? I dont use any threads.
You should avoid modifying elements in a list while iterating that list.
With the for (int i...) loop, you are not iterating the list, so you can modify the elements inside.
In the for (Baseitem item : list) loop, you are iterating the list, so the modification of the elements of the list will raise the ConcurrentModificationException exception.
You have to use the first form of the loop if you want to modify the elements inside it.
以上就是发生这种异常的表面现象。
本文探讨了在Java中使用ArrayList进行迭代时遇到的ConcurrentModificationException异常问题。通过对比两种不同的迭代方式,解释了为何增强for循环会导致该异常,并提出了避免此问题的方法。

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



