java.lang.IndexOutOfBoundsException

Jav*_*mer 1 java arrays runtime-error arraylist indexoutofboundsexception

我使用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]);
}
Run Code Online (Sandbox Code Playgroud)

我收到一个java.lang.IndexOutOfBoundsException看起来像这样的错误:Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 42, Size: 79

为什么即使通过索引号不等于或大于大小,我也会得到错误?该程序仍然像正常运行,但我仍然不希望它有任何错误.

我也尝试过的enchanced for循环,但后来我得到一个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]);
}
Run Code Online (Sandbox Code Playgroud)

Dun*_*nes 7

ConcurrentModificationException在使用增强型for循环时得到的事实意味着另一个线程在您迭代它时修改您的列表.

出于同样的原因,在使用普通for循环进行循环时会出现不同的错误 - 列表的大小会发生变化,但只会检查size()循环入口处的约束.

有许多方法可以解决此问题,但可能有一种方法是确保对列表的所有访问都是同步的.