java - For-Each能够遍历数组(Array)的原理是什么?
迷茫
迷茫 2017-04-18 10:53:36
0
2
764

比如这样一个例子...

Egg[] eggs = {new Egg(), new Egg()};
for (Egg egg : eggs) {
    egg.eat();
}

自己尝试了一下,冒号后面的对象只要不是数组或者Iterable对象,都是会报出编译错误。
Can only iterate over an array or an instance of java.lang.Iterable

然后我通过调试发现For-Each实际上是不断地调用迭代器的hasNext()和next()方法来实现对Collection类遍历的。

那么遍历数组的原理是什么呢?也是在JDK层面实现的吗?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!