我使用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]);
}我得到一个java.lang.IndexOutOfBoundsException错误,如下所示:Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 42, Size: 79
为什么即使通过索引数不等于或大于大小,我也会得到错误?该程序仍然正常运行,但我仍然不希望它有任何错误。
我也尝试过一个增强的循环,但是后来我得到了一个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]);
}发布于 2014-01-02 14:17:21
在使用增强型for循环时,您获得了一个ConcurrentModificationException,这意味着另一个线程在遍历列表时正在修改它。
由于同样的原因,在循环使用普通for循环时会出现不同的错误--列表的大小会发生变化,但您只能在循环的条目处检查size()约束。
解决这个问题的方法有很多,但一种可能是确保对列表的所有访问都是已同步。
发布于 2014-01-02 14:24:38
您是否使用多个线程?这个问题的公认答案可能会帮助您处理IndexOutOfBoundsException。
当您在迭代列表时试图修改(编辑、删除、重新排列或更改)列表时,会引发ConcurrentModificationException。例如:
//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
复制相似问题