【问题标题】:Using an iterator with an enhanced for loop in Java?在 Java 中使用带有增强 for 循环的迭代器?
【发布时间】:2016-01-05 13:47:33
【问题描述】:

好的,所以在我的类项目中,我正在查看我的类“Sprite”的 ArrayList,并带有增强的 for 循环,我偶尔需要删除我正在查看的 Sprite。我被告知我可以使用迭代器安全地执行此操作(即不删除我当前正在查看的 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,则需要从 ArrayList 中删除 s。

【问题讨论】:

  • 很确定你不能,因为你需要调用Iteratorsremove方法
  • 您需要更旧的 for 循环才能安全地删除项目。外部 for 循环必须从最大长度开始,例如 for(int i = sprites.size(); i >= 0; i--)。否则,可能是ConcurrentModificationException 的原因。内循环没问题。

标签: java loops for-loop iterator


【解决方案1】:

您需要使用迭代器本身循环(和删除)。

for (Sprite s : sprites) {

应该改为,

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

然后您的if 条件将是,

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

【讨论】:

  • 你应该使用Iterator&lt;Sprite&gt;
  • 好的,谢谢!似乎工作得很好,但是 s 是如何增加的?我看到 s=it.next,但 it.next 不是每次都一样吗?还是 it.hasNext 会自动增加它还是什么?
  • @user3304654: next 都将光标移动到下一个元素并返回它。我本来打算告诉你去看看 the documentation 但我发现它实际上并不是 100 % 清楚的!
【解决方案2】:

除了@Codebender 回答:要限制迭代器变量的范围,可以使用普通的for 循环:

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

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

这样it 变量在循环之后是未定义的。

【讨论】:

    猜你喜欢
    • 2015-11-03
    • 2023-03-30
    • 2014-11-16
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    相关资源
    最近更新 更多