[英]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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.