考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
如果不使用for each语法,等价的for循环会是什么样子?
考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
如果不使用for each语法,等价的for循环会是什么样子?
当前回答
Java“for each”循环构造将允许对两种类型的对象进行迭代:
T[](任何类型的数组)java.lang.Iterable<T>
Iterable<T>接口只有一个方法:Iterator<T>迭代器()。这对Collection<T>类型的对象有效,因为Collection<T<接口扩展了Iterable<T>。
其他回答
这是一个等价的表达式。
for(Iterator<String> sit = someList.iterator(); sit.hasNext(); ) {
System.out.println(sit.next());
}
还要注意,在原始问题中使用“foreach”方法确实有一些限制,例如在迭代过程中无法从列表中删除项目。
新的for循环更容易阅读,并且不需要单独的迭代器,但只有在只读迭代过程中才能真正使用。
我认为这会奏效:
for (Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String x = i.next();
System.out.println(x);
}
代码应为:
import java.util.ArrayList;
import java.util.List;
public class ForLoopDemo {
public static void main(String[] args) {
List<String> someList = new ArrayList<String>();
someList.add("monkey");
someList.add("donkey");
someList.add("skeleton key");
// Iteration using For Each loop
System.out.println("Iteration using a For Each loop:");
for (String item : someList) {
System.out.println(item);
}
// Iteration using a normal For loop
System.out.println("\nIteration using normal For loop: ");
for (int index = 0; index < someList.size(); index++) {
System.out.println(someList.get(index));
}
}
}
使用较旧的Java版本(包括Java7),可以使用foreach循环,如下所示。
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
for(String item : items) {
System.out.println(item);
}
以下是Java8中使用for-each循环的最新方法(使用forEach+lambda表达式或方法引用循环List)。
Lambda公司
// Output: A,B,C,D,E
items.forEach(item->System.out.println(item));
方法参考
// Output: A,B,C,D,E
items.forEach(System.out::println);
有关详细信息,请参阅“Java 8 For Each examples”。