簡體   English   中英

如何在 Java 中編寫通用的 foreach 循環?

[英]How do I write a generic foreach loop in Java?

到目前為止,我有以下代碼:

/*
 * 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)來完成這項工作?

這樣的事情應該做:

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

E 是集合,c 是循環內的變量 for(E c: toBeAdded )...

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

您可以用 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;
}
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM