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]);
}
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.
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