[英]java.lang.IndexOutOfBoundsException
I use ArrayList to store the 'shadows' for every rectangle in the level but when I iterate through the like this: 我使用ArrayList为关卡中的每个矩形存储“阴影”,但是当我像这样迭代时:
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
我收到一个看起来像这样的
java.lang.IndexOutOfBoundsException
错误: 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 我也尝试过强化循环,但后来却得到了
java.util.ConcurrentModificationException
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. 使用增强的for循环时收到
ConcurrentModificationException
的事实意味着,在迭代列表时,另一个线程正在修改列表。
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. 出于相同的原因,使用普通的for循环进行循环时,您会收到不同的错误-列表的大小发生了变化,但是您仅在循环的入口处检查了
size()
约束。
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.
该问题的可接受答案可能会帮助您解决IndexOutOfBoundsException。
A ConcurrentModificationException is thrown when you try to modify (edit, delete, rearrange, or change somehow) a list while iterating over it. 当您尝试在迭代列表时修改(编辑,删除,重新排列或以某种方式更改)列表时,抛出ConcurrentModificationException。 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.