【问题标题】:java.lang.IndexOutOfBoundsExceptionjava.lang.IndexOutOfBoundsException
【发布时间】: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


【解决方案1】:

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

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

有很多方法可以解决这个问题,但其中一种方法可能是确保对列表的所有访问权限都是synchronized

【讨论】:

  • 谢谢,我只需要将更新方法移到 for 循环之后
【解决方案2】:

您是否使用多个线程? The accepted answer in this question 可能会帮助您解决 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
}

【讨论】:

    猜你喜欢
    • 2018-07-03
    • 2014-02-17
    • 2023-03-28
    • 2019-09-10
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多