开发者

How do I write a generic foreach loop in Java?

I have the following code so far:

/*
 * 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;
    }
}

My question is: what do I replace something (and c) with to make this work?


Something like this should do:

// 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;
}

The general form is:

for (TypeOfElements iteratorVariable : collectionToBeIteratedOver) `


It's pretty simple to write a foreach in Java.

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

You can do foreach with either an iteratable or array. Be aware that if you don't typecheck your iterator (Iterator), then you need to use Object for ObjectType. Otherwise use whatever E is. For example

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

For your case:

   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;
    }


E is the collection, c is the variable inside the loop for(E c : toBeAdded ) ...


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;
}

Also take a look at Collections.addAll


You can write the foreach loop in 2 ways and they are equivalent.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜