比如这样一个例子...
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层面实现的吗?
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:
This is also a syntax sugar provided by the JVM for Java.