簡體   English   中英

嘗試從ArrayList中刪除元素

[英]Attempting to remove element from ArrayList

我正在嘗試創建一個類,該類將顯示文本幾秒鍾,然后消失。

我正在使用LWJGL,在我的主類MetalCLicker中,我有一個for循環,該循環循環彈出窗口。

            for(PopUp pop: popups){
            pop.tick(pop);
        }

popup類:(刻度方法底部的問題)public class PopUp {

MetalClicker game;

int x;
float y, lifetime;
String line1, line2, line3;
Color color;

private UnicodeFont font;


public PopUp(MetalClicker game, int x, int y, float lifetime, String line1, String line2, String line3, Color color){
    this.x = x;
    this.y = y;
    this.lifetime = lifetime*game.fps;
    this.line1 = line1;
    this.line2 = line2;
    this.line3 = line3;
    this.color = color;
    this.game = game;


    font = new UnicodeFont(new java.awt.Font ("Vani", Font.BOLD, 12));
    font.getEffects().add(new ColorEffect(java.awt.Color.white));
    font.addNeheGlyphs();
    try {
        font.loadGlyphs();
    } catch (SlickException e) {
        e.printStackTrace();
    }
}

public void render(){
    font.drawString(x - (line1.length()/2), y, line1, color);
    font.drawString(x - (line2.length()/2), y+14, line2, color);
    font.drawString(x - (line3.length()/2), y+28, line3, color);
}

public void tick(PopUp pop){
    y -= 3/lifetime;

    lifetime -= 1;
    if (lifetime == 0) game.popups.remove(pop); //problem resides here
    else render();
}
}

生命周期為0時,程序崩潰,因此嘗試刪除該元素。 在刪除行之前和之后都成功地打印出行,所以我現在很困惑:(

我嘗試在tick方法中使用此方法,因此我切換為在參數中發送實際元素。

控制台中沒有錯誤,但是調試告訴我ArrayList $ Itr.next()行:831 ArrayList $ Itr.checkForComodification()行:859 [本地變量不可用]

內部線程[main]

如果需要,我會用更多信息來更新帖子,但是我想不出該說些什么來幫助您,幫助我。

而且有關如何在我的方法參數中不使用MetalCLicker游戲的情況下進行操作的信息很酷。

您嘗試在遍歷列表時刪除元素,從而使迭代器無效。 您不能使用此:

for(PopUp pop: popups) {
  popups.remove(pop); // effectively, due to tick
}

甚至安全地:

for(var i=0, last=popups.size(); i<last; i++) {
  PopUp pop = popups.get(i);
  popups.remove(pop); // next "i++" will skip over an item
}

但是,您可以使用以下命令:

for(var i=popups.size()-1; i>=0; i--) {
  PopUp pop = popups.get(i);
  popups.remove(pop);
}

因為現在所有刪除都發生在數組列表的一部分中,下次迭代不會涉及

您不能在一個集合周圍循環並同時直接從其中刪除一個項目。 您在此處有兩個選擇,您可以將此集合單獨復制到循環的新集合中,也可以不使用foreach ,而直接使用集合迭代器並將迭代器作為參數發送給tick方法,然后可以調用集合迭代器上的remove方法,它不會引發此異常。

因此,可以將foreach更改為:

for(PopUp pop : popups.clone()){
    pop.tick(pop);
}

或使用迭代器代替foreach:

Iterator<PopUp> iterator = popups.iterator();
while ( iterator.hasNext() ) {
  PopUp pop = iterator.next();
  pop.tick(iterator);
}

tick實現中:

public void tick(Iterator it){
    y -= 3/lifetime;

    lifetime -= 1;
    if (lifetime == 0) {
      it.remove();
    }
    else render();
}

兩者的效果大致相同,但我想說第二種選擇更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM