from:http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work
forEach是JDK1.5以后出现的新特性,那么以下这段forEach代码和普通的for循环又有什么不同呢?
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
该代码编译过程中实际上会被翻译成以下代码。
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
这适用于实现了Iterable
接口的类。
此外对于数组来说,就会使用一个下标,每次遍历时检查是否到达数组的边界,如果不就前进一步,就和普通的for写法一样。
int[] test = new int[] {1,4,5,7};
for (int intValue : test) {
// do some work here on intValue
}
int[] test = new int[] {1,4,5,7};
for (int i = 0; i < test.length; i++) {
int intValue = test[i];
// do some work here on intValue
}