好吧,在我的课程项目中,我正在通过一个带有增强for循环的我的类“Sprite”的ArrayList,并且偶尔需要删除我正在查看的Sprite。我被告知我可以安全地做到这一点(即不删除我目前正在看的精灵)与迭代器。我看着它在Oracle的Java文档,但我真的不明白它..在Java中使用增强for循环的迭代器?
这里是我的方法:
public void forward() {
for (Sprite s : sprites) {
s.move();
for(Sprite x : sprites){
if(s!=x && s.overlaps(x)){
if(s instanceof Razorback && x instanceof Opponent){
x.hit();
}
if(x instanceof Razorback && s instanceof Opponent){
s.hit();
}
}
}
if(s.shouldRemove())
sprites.remove(s);
}
}
如果(s.shouldRemove())是我需要实现一个迭代器。如果shouldRemove()返回true,则需要从ArrayList中删除s。
很确定你不能,因为你需要调用Iterators'' remove'方法 – MadProgrammer
你需要更老的for循环来安全地移除物品。 Outter for循环必须从最大长度开始,比如'for(int i = sprites.size(); i> = 0; i - )'。否则,它可能是'ConcurrentModificationException'的原因。内循环是好的。 –