简体   繁体   English

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

[英]Using an iterator with an enhanced for loop in Java?

Okay so in my project for class I'm looking through an ArrayList of my class "Sprite" with an enhanced for loop, and I occasionally need to delete the Sprite that I'm looking at. 好的,所以在我的班级项目中,我正在遍历带有增强型for循环的班级“ Sprite”的ArrayList,有时我需要删除正在查看的Sprite。 I'm told I can do this safely (ie not deleting the Sprite I'm currently looking at) with Iterators. 有人告诉我可以使用Iterators安全地执行此操作(即,不删除当前正在查看的Sprite)。 I looked it up on Oracle's java documentation but I don't really understand it.. 我在Oracle的Java文档中查找了它,但我不太了解。

Here's my method: 这是我的方法:

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()) is where I need to implement an iterator. if(s.shouldRemove())是我需要实现迭代器的地方。 If shouldRemove() return true, s needs to be removed from the ArrayList. 如果shouldRemove()返回true,则需要将s从ArrayList中删除。

You need to loop (and remove) using the iterator itself. 您需要使用迭代器本身进行循环(并删除)。

for (Sprite s : sprites) {

should be changed to, 应该改为

Iterator<Sprite> it = sprites.iterator();
while (it.hasNext()) {
    Sprite s = it.next();

And then your if condition will be, 然后你if条件将是,

if (s.shouldRemove())
    it.remove();

In addition to @Codebender answer: to limit the scope of the iterator variable, you can use plain for loop: 除了@Codebender答案:要限制迭代器变量的范围外,您还可以使用普通的for循环:

for(Iterator<Sprite> it = sprites.iterator(); it.hasNext(); ) {
    Sprite s = it.next();

    ...
    if (s.shouldRemove())
        it.remove();
}

This way the it variable is undefined after the loop. 这样,循环后未定义it变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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