好吧,在我的課程項目中,我正在通過一個帶有增強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'的原因。內循環是好的。 –