试图从ArrayList中删除元素

时间:2013-11-28 02:47:25

标签: java arraylist lwjgl

我正在尝试创建一个类,它将显示文本几秒钟然后消失。

我正在使用LWJGL,在我的主类MetalCLicker中,我有一个for循环,循环播放弹出窗口。

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

弹出类:(在tick方法底部出现问题)         公共课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 [局部变量不可用]

在Thread [main]

如果需要,我会更新帖子以获取更多信息,但我无法想到要帮助你的内容,请帮助我。

关于如何在我的方法参数中不使用MetalCLicker游戏进行操作的信息会很酷。

2 个答案:

答案 0 :(得分:1)

你试图在迭代列表时删除元素,从而使迭代器无效。你不能用这个:

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);
}

因为任何删除现在都发生在数组列表中不会被下一次迭代触及的部分

答案 1 :(得分:0)

您无法循环收集并同时直接从中删除项目。这里有两个选项,你可以将这个集合复制到一个新的集合中,或者你可以直接使用集合迭代器而不是使用foreach,并将迭代器作为参数发送给{{1然后你可以在集合迭代器中调用remove方法,它不会抛出这个异常。

所以要么将tick更改为:

foreach

或使用迭代器而不是foreach:

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

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

tick

两者的效果大致相同,但我会说第二种选择更好。