Java, ArrayList and Exception in thread “AWT-EventQueue-0” java.util.ConcurrentModificationException

来源:互联网 发布:万网中文域名注册 编辑:程序博客网 时间:2024/05/17 18:43

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.


以上就是发生这种异常的表面现象。














0 0