Prior to release 1.5, this was the preferred idiom for iterating over a collection:

// No longer the preferred idiom to iterate over a collection!

for (Iterator i = c.iterator(); i.hasNext(); ) {

doSomething((Element) i.next()); // (No generics before 1.5)

}

This was the preferred idiom for iterating over an array:

// No longer the preferred idiom to iterate over an array!

for (int i = 0; i < a.length; i++) {

doSomething(a[i]);

}

// The preferred idiom for iterating over collections and arrays

for (Element e : elements) {

doSomething(e);

}

Advantage of for-each loop

  1. Slight performance advantage over an ordinary for loop since it computes the limit of the array index only once.
  1. It's not error propone for Nested iteration over multiple collections.

    // Preferred idiom for nested iteration on collections and arrays

    for (Suit suit : suits)

    for (Rank rank : ranks)

    deck.add(new Card(suit, rank));

  2. It lets you iterate over any object that implements the Iterable interface.

    public interface Iterable<E> {

    // Returns an iterator over the elements in this iterable

    Iterator<E> iterator();

    }

Three common situations where you can't use a for-each loop

  1. Filtering— If you need to traverse a collection and remove selected elements, then you need to use an explicit iterator so that you can call its remove method.
  2. Transforming—If you need to traverse a list or array and replace some or all of the values of its elements, then you need the list iterator or array index in order to set the value of an element.
  3. Parallel iteration—If you need to traverse multiple collections in parallel, then you need explicit control over the iterator or index variable, so that all iterators or index variables can be advanced in lockstep (as demonstrated unintentionally in the buggy card and dice examples above).

Summary

The for-each loop provides compelling advantages over the traditional for loop in clarity and bug prevention, with no performance penalty. You should use it wherever you can.

Effective Java 46 Prefer for-each loops to traditional for loops的更多相关文章

  1. Effective Java 69 Prefer concurrency utilities to wait and notify

    Principle Use the higher-level concurrency utilities instead of wait and notify for easiness. Use Co ...

  2. Effective Java 35 Prefer annotations to naming patterns

    Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...

  3. Effective Java 53 Prefer interfaces to reflection

    Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...

  4. Effective Java 68 Prefer executors and tasks to threads

    Principle The general mechanism for executing tasks is the executor service. If you think in terms o ...

  5. Effective Java 18 Prefer interfaces to abstract classes

    Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...

  6. Effective Java 20 Prefer class hierarchies to tagged classes

    Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...

  7. Effective Java 25 Prefer lists to arrays

    Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...

  8. Effective Java 49 Prefer primitive types to boxed primitives

    No. Primitives Boxed Primitives 1 Have their own values Have identities distinct from their values 2 ...

  9. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

随机推荐

  1. IIS app pools, worker processes, app domains

    Copy from  http://stackoverflow.com/questions/14105345/iis-app-pools-worker-processes-app-domains I ...

  2. AutoMapper配置方法

    在Mvc开发中,我们经常需要构建一个viewModel出来供页面使用,在PO和VO之间相互传值的时候,如果实体字段比较多的时候,那么传值将变得异常麻烦,也使得代码非常的臃肿.AutoMapper可以帮 ...

  3. Winform开发框架之权限管理系统改进的经验总结(3)-系统登录黑白名单的实现

    在一般的权限系统里面,可能经常会看到系统的黑名单或者白名单的拦截功能.在一般权限系统里面,常见的黑名单就是禁止用户在某些IP上登录系统,白名单就是允许用户只在某些IP上登录系统.本随笔主要介绍在我的权 ...

  4. css 样式表

    CSS(cascading style sheets,层叠样式表),作用是美化HTML网页. /*注释*/   注释语法 2.1 样式表的基本概念 2.1.1样式表的分类 1.内联样式表 和HTML联 ...

  5. jQuery中的动画与特效

    1.显示和隐藏hide()和show() 对于动画来说,显示和隐藏是最基本的效果之一,简单介绍jQuery的显示和隐藏. <script type="text/javascript&q ...

  6. 个人信息管理PIM——密码管理工具软件

    密码管理工具 以KeePass为主,结合LastPass在线浏览器网页密码.有钱银可以考虑1Password. KeePass LastPass 1Password 价格费用 免费开源 普通版:免费 ...

  7. x3dom 1.6 发布

    X3DOM 库的1.6版本发布了,以下是最重要的一些变化: 完整的新的文档频道 -  http://doc.x3dom.org x3dom实例频道 - http://examples.x3dom.or ...

  8. ahjesus ubuntu10.4安装ruby2.1.1

    sudo apt-get install python-software-properties sudo apt-add-repository ppa:brightbox/ruby-ng sudo a ...

  9. CentOS6.5 FTP配置

    一:安装vsftpd 查看是否已经安装vsftpd rpm -qa | grep vsftpd 如果没有,就安装,并设置开机启动 yum -y install vsftpd chkconfig vsf ...

  10. 求Mac 的adt插件!

    搞了半天原来ADT Mac和win是通用的安装方法也相同! 自己配环境! 下载一个Eclipse,然后安装就行! dns:203.195.223.190 这个DNS可以连上谷歌的服务器(只限学习使用) ...