好吧,在我的类项目中,我正在通过增强的for循环查看我的类"Sprite"的ArrayList,我偶尔需要删除我正在查看的Sprite.我被告知我可以安全地执行此操作(即不删除我正在查看的Sprite)与迭代器.我在Oracle的java文档中查了一下,但我真的不明白它..
这是我的方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
if(s.shouldRemove())是我需要实现迭代器的地方.如果shouldRemove()返回true,则需要从ArrayList中删除s.