如何在Java中编写通用的foreach循环?

时间:2011-06-08 19:17:45

标签: java foreach

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

/*
 * 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)以使其发挥作用?

5 个答案:

答案 0 :(得分:9)

这样的事情应该做:

// 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) `

答案 1 :(得分:1)

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

答案 2 :(得分:1)

用Java编写foreach非常简单。

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

您可以使用iteratable或array执行foreach。请注意,如果您没有检查迭代器(Iterator),则需要使用Object for 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;
    }

答案 3 :(得分:0)

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

答案 4 :(得分:0)

你可以用两种方式编写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;
}