【发布时间】:2014-01-20 00:19:39
【问题描述】:
我使用 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
为什么即使索引号不等于或大于大小,我也会收到错误消息?程序仍然正常运行,但我仍然不希望它出现任何错误。
我也尝试了增强的 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]);
}
【问题讨论】:
-
你是在不同的线程中修改这个数组列表吗?
-
fillPolygon()是否修改了shadows? -
什么是
shadows.size()? -
尝试使用“volatile”,您可能希望通过列表使用迭代器,并确保没有其他任何东西同时修改您的列表,否则您将需要使用同步访问
标签: java arrays arraylist runtime-error indexoutofboundsexception