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

4 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我应该用什么来替换某些东西(和c)以使其工作?

aio*_*obe 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;
}
Run Code Online (Sandbox Code Playgroud)

一般形式是:

for (TypeOfElements iteratorVariable : collectionToBeIteratedOver) `
Run Code Online (Sandbox Code Playgroud)