java.lang.IndexOutOfBoundsException

﹥>﹥吖頭↗ 提交于 2019-12-02 05:32:45

The fact that you get a ConcurrentModificationException when using an enhanced for loop means that another thread is modifying your list while you iterate across it.

You get a different error when looping with a normal for loop for the same reason - the list changes in size but you only check the size() constraint at the entry to the loop.

There are many ways to solve this problem, but one might be to ensure all access to the list is synchronized.

Hernán Erasmo

Are you using more than one thread? The accepted answer in this question might help you regarding the IndexOutOfBoundsException.

A ConcurrentModificationException is thrown when you try to modify (edit, delete, rearrange, or change somehow) a list while iterating over it. For example:

//This code would throw a ConcurrentModificationException
for(Duck d : liveDucks){
    if(d.isDead()){
        liveDucks.remove(d);
    }
}

//This could be a possible solution
for(Duck d : liveDucks){
    if(d.isDead()){
        deadDucks.add(d);
    }
}

for(Duck d : deadDucks){
    liveDucks.remove(d);  //Note that you are iterating over deadDucks but modifying liveDucks
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!