【问题标题】:How do I write a generic foreach loop in Java?如何在 Java 中编写通用的 foreach 循环?
【发布时间】:2011-06-08 19:17:45
【问题描述】:

到目前为止,我有以下代码:

/*
 * This method adds only the items that don’t already exist in the
 * ArrayCollection. If items were added return true, otherwise return false.
 */
public boolean addAll(Collection<? extends E> toBeAdded) {

    // Create a flag to see if any items were added
    boolean stuffAdded = false;


    // Use a for-each loop to go through all of the items in toBeAdded
    for (something : c) {

        // If c is already in the ArrayCollection, continue
        if (this.contains(c)) { continue; }     

            // If c isn’t already in the ArrayCollection, add it
            this.add(c)
            stuffAdded = true;
        }

        return stuffAdded;
    }
}

我的问题是:我应该用什么替换某些东西(和 c)来完成这项工作?

【问题讨论】:

  • this.contains()?你的对象实现了 Collection 吗?
  • @Cosmin,可能是因为他在这里实现addAll :-)

标签: java foreach


【解决方案1】:

应该这样做:

// Use a for-each loop to go through all of the items in toBeAdded
for (E c : toBeAdded) {

    // If c is already in the ArrayCollection, continue
    if (this.contains(c)) {
        continue;
    }

    // If c isn’t already in the ArrayCollection, add it
    this.add(c);

    stuffAdded = true;
}

一般形式为:

for (TypeOfElements iteratorVariable : collectionToBeIteratedOver) `

【讨论】:

  • 方法调用前不需要this
【解决方案2】:

用 Java 编写 foreach 非常简单。

for(ObjectType name : iteratable/array){ name.doSomething() }

您可以使用可迭代或数组来执行 foreach。请注意,如果您不对您的迭代器(Iterator)进行类型检查,那么您需要将 Object 用于 ObjectType。否则使用 E​​ 是什么。例如

ArrayList<MyObject> al = getObjects();
for(MyObject obj : al){
  System.out.println(obj.toString());
}

对于您的情况:

   for(E c : toBeAdded){
        // If c is already in the ArrayCollection, continue
        if( this.contains(c) ){ continue;}     

        // If c isn’t already in the ArrayCollection, add it
        this.add(c)
        stuffAdded = true;
    }

【讨论】:

  • *不是一个迭代tor,而是一个迭代ble
【解决方案3】:

E是集合,c是循环内的变量 for(E c : toBeAdded ) ...

【讨论】:

  • E 不是集合。 E 是循环中变量的类型。
【解决方案4】:
public boolean addAll(Collection<? extends E> toBeAdded) {
    boolean stuffAdded = false;
    for(E c : toBeAdded){
        if(!this.contains(c)){
             this.add(c)
             stuffAdded = true;
        }
    }
    return stuffAdded;
}

也可以看看Collections.addAll

【讨论】:

  • 这是他正在实现的addAll 方法! :D
  • 对不起。我只是认为使用一些 SET 作为内部存储会更好。
  • 你确定吗?即使您在 Sun 工作并被分配执行 ArrayList?
  • 不,当然:) 我可以假设这种情况下可以实现集合。
【解决方案5】:

你可以用 2 种方式编写 foreach 循环,它们是等效的。

List<Integer> ints = Arrays.asList(1,2,3);
int s = 0;
for (int n : ints) { s += n; }

for (Iterator<Integer> it = ints. iterator(); it.hasNext(); ) {
    int n = it.next();
    s += n;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 2016-05-09
    相关资源
    最近更新 更多