【发布时间】:2014-10-18 04:58:22
【问题描述】:
最近我完全被我的代码中的一个奇怪的错误弄糊涂了,到了极度沮丧的地步。最后,我在我的代码中输入了System.out.println();,直到我缩小范围,以揭示最奇怪的结果。代码如下:
for (Iterator<Integer> it = list.iterator(); it.hasNext();) {
i = it.next();
System.out.println(DeathWish.getInstanceListReference()
.get(DeathWish.getInstanceListReference().size() -1) );
System.out.println("Golden number: " +
(DeathWish.getInstanceListReference().size() -1) );
System.out.println((DeathWish.getInstanceListReference().size() -1) == i);
System.out.println("CurrentInstance List: " +
Arrays.toString(DeathWish.getInstanceListReference().toArray()));
System.out.println("Iteration: " + i);
try {
System.out.println( DeathWish.getInstanceListReference()
.remove((int)list.get(i))); //remove unwanted objects from game paint list
} catch(IndexOutOfBoundsException ex) {
System.err.println(ex + " Error with multiple GameObj objects");
} finally {
System.out.println("\n");
}
}
和输出:
DeathWish.Bullet@ddd5de
Golden number: 2
true
CurrentInstance List: [DeathWish.Player@3a5cf7, DeathWish.Bullet@6cca54, DeathWish.Bullet@ddd5de]
Iteration: 2
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 Error with multiple GameObj objects
getInstanceListReference() 返回一个ArrayList<GameObj>。 GameObj 是我项目中代表游戏对象的超超类之一。此外,getInstanceListReference() 返回的ArrayList 在运行时不会被内部源代码修改。
在for循环之前执行了一些代码:
System.out.println("\n------------------------\n" + "Read Instance List: " + Arrays.toString(tmpLock.toArray()) + "|" + Arrays.toString(tmpLock1.toArray()));
System.out.println("Recycle Bin: " + recycleBin.get(0) + "|" + recycleBin.get(1) + "\n------------------------\n");
源代码中最顶部的这个列表指的是recycleBin。它保存计划删除的对象的索引。带有IndexOutOfBoundsException 的for 循环循环遍历recycleBin 中的整数,并利用它们删除实例列表中的索引。
我是否在做一些我不知道导致问题的不良做法?
【问题讨论】:
-
发帖SSCCE
-
您确定您没有从其他线程访问该列表吗?尝试围绕对 listReference 的所有访问添加 synchronized(),它是在其中写入和读取的。这有强烈的线程问题的味道。
-
是的,我确定我没有从另一个线程访问。为了更好地衡量,我将同步修饰符添加到我的 get 方法中。我无法将同步修饰符添加到 ArrayList 引用本身,因为我正在使用封装(对于新手:引用有一个私有修饰符和一个 get 方法来将值传递给其他类)。
-
你们肯定还没有“发现 Java 的错误”,这不应该是您跳到的第一个解释。您在 您的代码 中发现错误的可能性远。如果您按照建议发布 SSCCE,我们可以帮助您调试和理解它。
-
你没有抓住重点——你的代码的其余部分(大概)不是问题的原因。尝试通过删除理论上不相关的代码来复制问题。例如,就像 sscce.org 建议的那样,如果这不是问题的一部分,请删除任何图形界面。在这里,我认为你可以去掉匿名类,然后迭代,比如说,一个整数列表。如果您的代码如此复杂且相互关联,以至于无法提取较小的组件,那么这是您的错误做法;将您的代码构造成可以单独测试的独立部分。
标签: java debugging runtime-error iteration indexoutofboundsexception