java.lang.IndexOutOfBoundsException

两盒软妹~` 提交于 2019-12-20 04:30:26

问题


I use ArrayList to store the 'shadows' for every rectangle in the level but when I iterate through the like this:

for(int n = 0; n < shadows.size(); ++n){
 g2d.fillPolygon(shadows.get(n)[0]);
 g2d.fillPolygon(shadows.get(n)[1]);
 g2d.fillPolygon(shadows.get(n)[2]);
 g2d.fillPolygon(shadows.get(n)[3]);
 g2d.fillPolygon(shadows.get(n)[4]);
 g2d.fillPolygon(shadows.get(n)[5]);
}

I get a java.lang.IndexOutOfBoundsException error that looks like this: Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 42, Size: 79

Why do I get the error even through the index number isn't equal or more than the size? The program still runs like normal but I still don't want it to have any errors.

I have also tried an enchanced for loop but then I get a java.util.ConcurrentModificationException instead

for(Polygon[] polys : shadows){
 g2d.fillPolygon(polys[0]);
 g2d.fillPolygon(polys[1]);
 g2d.fillPolygon(polys[2]);
 g2d.fillPolygon(polys[3]);
 g2d.fillPolygon(polys[4]);
 g2d.fillPolygon(polys[5]);
}

回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/20884857/java-lang-indexoutofboundsexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!