繁体   English   中英

在Java中使用带有增强的for循环的迭代器?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM