[英]Using an iterator with an enhanced for loop in Java?
好的,所以在我的班級項目中,我正在遍歷帶有增強型for循環的班級“ Sprite”的ArrayList,有時我需要刪除正在查看的Sprite。 有人告訴我可以使用Iterators安全地執行此操作(即,不刪除當前正在查看的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);
}
}
if(s.shouldRemove())是我需要實現迭代器的地方。 如果shouldRemove()返回true,則需要將s從ArrayList中刪除。
您需要使用迭代器本身進行循環(並刪除)。
for (Sprite s : sprites) {
應該改為
Iterator<Sprite> it = sprites.iterator();
while (it.hasNext()) {
Sprite s = it.next();
然后你if
條件將是,
if (s.shouldRemove())
it.remove();
除了@Codebender答案:要限制迭代器變量的范圍外,您還可以使用普通的for
循環:
for(Iterator<Sprite> it = sprites.iterator(); it.hasNext(); ) {
Sprite s = it.next();
...
if (s.shouldRemove())
it.remove();
}
這樣,循環后未定義it
變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.