【发布时间】:2013-06-28 22:41:34
【问题描述】:
我不明白为什么这个方法会抛出异常:
public void add(Object obj){
gameObjects.add(obj); //here the exception happens
}
...虽然这个没有:
public void add(Object obj){
gameObjects.add(obj); // no exception actually happens here
gameObjects.remove(obj);
}
考虑到这是运行时异常,为什么会发生这种情况?
例外:
Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at threads.Main.tick(Main.java:181)
at threads.Main.run(Main.java:104)
该方法为对象内的刻度方法调用。
gameObjects 不为空:
List<Object> gameObjects = new ArrayList<Object>(128);
【问题讨论】:
-
信息不足。首先,有什么例外。另外,这些调用的上下文是什么?谁调用代码以及如何调用?
-
gameObjects是什么类型的?
-
gameObjects是什么?是空的吗? -
在遍历列表时修改列表(通过添加或删除元素)时发生 ConcurrentModificationException。
-
致所有反对者和密切投票者:如果他问为什么添加
.remove()调用会阻止抛出异常,那么这个问题实际上并没有那么糟糕。
标签: java concurrentmodification