java.lang.IndexOutOfBoundsException [英] java.lang.IndexOutOfBoundsException

查看:21
本文介绍了java.lang.IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ArrayList 来存储关卡中每个矩形的阴影",但是当我像这样迭代时:

for(int n = 0; n 

我收到一个 java.lang.IndexOutOfBoundsException 错误,如下所示:线程AWT-EventQueue-0"中的异常 java.lang.IndexOutOfBoundsException:索引:42,大小: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]);}

解决方案

当您使用增强的 for 循环时得到 ConcurrentModificationException 的事实意味着另一个线程正在修改您的列表,同时您遍历它.

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

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

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.

这篇关于java.lang.IndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆