从Java中的ArrayList中删除对象
我有这个,每当一个子弹达到大于我的屏幕宽度的位置时,它必须被销毁。当我尝试这个时,游戏崩溃。从Java中的ArrayList中删除对象
“bullet”是我的类,它包含我作为对象。
“子弹”是我的数组列表,包含所有的对象。
编辑:现在尝试迭代器,但仍然崩溃。
编辑:接受的答案帮助了我。现在工作。谢谢!
public ArrayList<bullet> bullets = new ArrayList<bullet>();
public Iterator<bullet> it = bullets.iterator();
while (it.hasNext()) {
bullet s = it.next();
if(s.xPosition > screenWidth - 10) {
it.remove();
}
}
在迭代它时,您无法从列表中删除元素。如果你这样做,你会得到ConcurrentModificationException
。 您应该使用迭代器并从迭代器中移除元素。
Iterator<Bullet> itr = bullets.iterator();
while(itr.hasNext()) {
if(itr.next().xPosition > screenWidth - 10) {
itr.remove(i);
}
}
的
那么,这是很酷的一切,但这并没有真正帮助我很多,因为我不知道如何制作其中的一个。 – 2013-02-11 13:53:01
@KevinJensenPetersen检查出您的问题下的评论张贴为评论。 – PermGenError 2013-02-11 13:53:39
更新上面.. – 2013-02-11 14:06:24
可能重复的[高效等效用于去除元件,同时重复所述收藏](http://*.com/questions/223918/efficient-equivalent-for-removing-elements-while-iterating-the-collection ) – 2013-02-11 13:50:22
你是什么意思?你有没有NullPointerException?你能更清楚地了解你的错误吗? – Dimitri 2013-02-11 13:54:18
更新以上.. – 2013-02-11 14:06:57