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

4
我已经有以下代码:

我已经有以下代码:

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

我的问题是:我需要用什么替换 something 和 c 才能使这个代码工作?

this.contains()?你的对象是否实现了Collection接口? - Cosmin Cosmin
@Cosmin,很可能是因为他在这里实现了addAll :-) - aioobe
5个回答

10
像这样的内容应该可以:
// 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 - Steve Kuo

1

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

不是迭代器,而是可迭代的。 - trutheality

0

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


1
E不是集合,E是循环中变量的类型。 - trutheality

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


这是他正在实现的 addAll 方法! :D - aioobe
抱歉,我认为最好使用一些SET作为内部存储。 - Nazarii Bardiuk
你确定吗?即使你曾在Sun工作并被分配实现ArrayList - aioobe
不,当然可以 :) 我可以假设可以为这种情况实现集合。 - Nazarii Bardiuk

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接