比如這樣一個例子...
Egg[] eggs = {new Egg(), new Egg()};
for (Egg egg : eggs) {
egg.eat();
}
自己嘗試了一下,冒號后面的對象只要不是數(shù)組或者Iterable對象,都是會報出編譯錯誤。
Can only iterate over an array or an instance of java.lang.Iterable
然后我通過調試發(fā)現(xiàn)For-Each實際上是不斷地調用迭代器的hasNext()和next()方法來實現(xiàn)對Collection類遍歷的。
那么遍歷數(shù)組的原理是什么呢?也是在JDK層面實現(xiàn)的嗎?
業(yè)精于勤,荒于嬉;行成于思,毀于隨。
Yes, this is just syntax sugar~ If you can foreach, you must implement the Iterable interface~
The principle that For-Each can traverse an array is that the JVM translates it into a traditional For-Index loop during compilation, that is:
for (int i = 0; i < arr.length; i++) {
...
}
This is also a syntax sugar provided by the JVM for Java.