- For-each语法内部,对collection是用nested iteratoration来实现的,对数组是用下标遍历来实现。
- Java 5 及以上的编译器隐藏了基于iteration和下标遍历的内部实现。(注意,这里说的是“Java编译器”或Java语言对其实现做了隐藏,而不是某段Java代码对其实现做了隐藏,也就是说,我们在任何一段JDK的Java代码中都找不到这里被隐藏的实现。这里的实现,隐藏在了Java 编译器中,我们可能只能像这篇帖子中说的那样,查看一段For-each的Java代码编译成的字节码,从中揣测它到底是怎么实现的了)
下面对“For-each”和“其对等的iteration/index实现”的对比再简洁明了不过了。
For-each loop | Equivalent for loop |
---|---|
for (type var : arr) { body-of-loop } | for (int i = 0; i < arr.length; i++) { type var = arr[i]; body-of-loop } |
for (type var : coll) { body-of-loop } | for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) { type var = iter.next(); body-of-loop } |
一定要注意For-each不是万能的,下面的场合是不适宜使用For-each的
Altho the enhanced for loop can make code much clearer, it can't be used in some common situations.
使用For-each时对collection或数组中的元素不能做赋值操作
- Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
同时只能遍历一个collection或数组,不能同时遍历多余一个collection或数组
- Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
遍历过程中,collection或数组中同时只有一个元素可见,即只有“当前遍历到的元素”可见,而前一个或后一个元素是不可见的。
- Only single element. Use only for single element access, eg, not to compare successive elements.
只能正向遍历,不能反向遍历(相比之下,C++ STL中还有reverse_iterator, rbegin(), rend()之类的东西,可以反向遍历)
- Only forward. It's possible to iterate only forward by single steps.
如果要兼容Java 5之前的Java版本,就不能使用For-each
-
- At least Java 5. Don't use it if you need compatibility with versions before Java 5.
此文章来自:http://blog.csdn.net/yasi_xi/article/details/25482173#t1