2013-02-11 108 views
0

我有這個,每當一個子彈達到大於我的屏幕寬度的位置時,它必須被銷燬。當我嘗試這個時,遊戲崩潰。從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(); 
      } 
     } 
+2

可能重複的[高效等效用於去除元件,同時重複所述收藏](http://stackoverflow.com/questions/223918/efficient-equivalent-for-removing-elements-while-iterating-the-collection ) – 2013-02-11 13:50:22

+0

你是什麼意思?你有沒有NullPointerException?你能更清楚地瞭解你的錯誤嗎? – Dimitri 2013-02-11 13:54:18

+0

更新以上.. – 2013-02-11 14:06:57

回答

2

在迭代它時,您無法從列表中刪除元素。如果你這樣做,你會得到ConcurrentModificationException。 您應該使用迭代器並從迭代器中移除元素。

Iterator<Bullet> itr = bullets.iterator(); 
while(itr.hasNext()) { 
    if(itr.next().xPosition > screenWidth - 10) { 
     itr.remove(i); 
    } 
} 
+0

那麼,這是很酷的一切,但這並沒有真正幫助我很多,因爲我不知道如何製作其中的一個。 – 2013-02-11 13:53:01

+0

@KevinJensenPetersen檢查出您的問題下的評論張貼爲評論。 – PermGenError 2013-02-11 13:53:39

+0

更新上面.. – 2013-02-11 14:06:24