亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

java - For-Each能夠遍歷數(shù)組(Array)的原理是什么?
迷茫
迷茫 2017-04-18 10:53:36
0
2
880

比如這樣一個例子...

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è)精于勤,荒于嬉;行成于思,毀于隨。

reply all(2)
大家講道理

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template