kooyee ‘s blog

开源软件, 众人努力的结晶, 全人类的共同财富
posts - 103, comments - 55, trackbacks - 0, articles - 66
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

[J2SE] For-each 循环

Posted on 2007-07-25 19:56 kooyee 阅读(259) 评论(0)  编辑  收藏 所属分类: Java

Java 5 之后终于能在java中使用for each 循环

for (type var : arr) {
    body
-of-loop
}

for (int i = 0; i < arr.length; i++
    type var 
= arr[i];
    body
-of-loop
}


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
            }


Where the for-each is appropriate

Altho the enhanced for loop can make code much clearer, it can't be used in some common situations.

  • Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
  • Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
  • Only single element. Use only for single element access, eg, not to compare successive elements.
  • Only forward. It's possible to iterate only forward by single steps.
  • At least Java 5. Don't use it if you need compatibility with versions before Java 5.

看来只能读取, 而不能写入值。而且不能进行太复杂的操作。


只有注册用户登录后才能发表评论。


网站导航: