考虑:
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循环会是什么样子?
当前回答
这是一个等价的表达式。
for(Iterator<String> sit = someList.iterator(); sit.hasNext(); ) {
System.out.println(sit.next());
}
其他回答
使用forEach:
int[] numbers = {1,2,3,4,5};
Arrays.stream(numbers).forEach(System.out::println);
答复:
1
2
3
4
5
The process finished with exit code 0
PS:您需要一个Array(int[]数字),然后导入java.util.Arrays;
如JLS中所定义的,每个循环的a可以有两种形式:
如果表达式类型是Iterable的子类型,则转换为:List<String>someList=newArrayList<String>();someList.add(“苹果”);someList.add(“球”);for(字符串项:someList){System.out.println(项);}//翻译为:for(Iterator<String>stringIterator=someList.iiterator();stringIterator.hasNext();){字符串项=stringIterator.next();System.out.println(项);}如果表达式必须具有数组类型T[],则:String[]someArray=新字符串[2];someArray[0]=“苹果”;someArray[1]=“球”;for(字符串项2:someArray){系统输出打印(第2项);}//翻译为:for(int i=0;i<someArray.length;i++){字符串item2=someArray[i];系统输出打印(第2项);}
Java8已经引入了一些流,这些流在适当大小的数据集中通常表现得更好。我们可以将它们用作:
someList.stream().forEach(System.out::println);
Arrays.stream(someArray).forEach(System.out::println);
代码应为:
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));
}
}
}
维基百科中提到的foreach循环的概念如下:
然而,与其他for循环构造不同,foreach循环通常保持没有明确的反击:他们基本上说“这样做而不是“做x次”。这样可以避免潜在的一个错误,使代码更容易阅读。
因此,foreach循环的概念描述了该循环不使用任何显式计数器,这意味着不需要使用索引在列表中遍历,因此它将用户从一个错误中解脱出来。为了描述这一错误的一般概念,让我们举一个使用索引在列表中遍历的循环的例子。
// In this loop it is assumed that the list starts with index 0
for(int i=0; i<list.length; i++){
}
但是假设列表以索引1开始,那么这个循环将抛出一个异常,因为它将在索引0处找不到元素,这个错误被称为off-by-one错误。因此,为了避免这一错误,使用了foreach循环的概念。可能还有其他优点,但这就是我认为使用foreach循环的主要概念和优点。
还要注意,在原始问题中使用“foreach”方法确实有一些限制,例如在迭代过程中无法从列表中删除项目。
新的for循环更容易阅读,并且不需要单独的迭代器,但只有在只读迭代过程中才能真正使用。