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. [前端]分享一个Bootstrap可视化布局的网站

    如果你像我一样:是个前端渣,能看懂css和html,略懂Bootstarp,懒! 当你每次都想独立完成一个web页面而不知道从哪里下手的时候,那么下面的这个网站,就是你所以需要的! http://ww ...

  2. Android学习笔记之Json的使用....

    PS:当你的能力还驾驭不了你的目标时,那你需要沉下心来历练... 学习内容: 1.Json的使用... 2.Json信息过滤... 3.从网络上获取Json数据... 4.解析Json数据获取各个属性 ...

  3. Sprint回顾

    1.回顾组织 主题:“我们下次怎么样才能更加认真对待?” 时间:设定为1至2个小时. 参与者:整个团队. 场所:能够在不受干扰的情况下讨论. 秘书:指定某人当秘书,筹备.记录.整理.  2.回顾流程 ...

  4. 数组(Array)的使用方法

    本文内容:        1.概述         2.数组基础         3.结合for循环与arr.length,在数组尾部插入数值         4.利用'concat','join'实 ...

  5. jquery 字符串转dom对象及对该对象使用选择器查询

    <script> $(document).ready(function () { var htmlStr = '<div id="outerDiv">< ...

  6. 分享AceAdminUI后台框架-你喜欢吗?

    距离上次写文章也很久了,这次分享一下自己刚刚看上的一款UI框架(自己买的),国外货,提供下载 第100位评论的我将会送出一个小礼物 礼物链接:http://yanghenglian.taobao.co ...

  7. 泛函编程(9)-异常处理-Option

    Option是一种新的数据类型.形象的来描述:Option就是一种特殊的List,都是把数据放在一个管子里:然后在管子内部对数据进行各种操作.所以Option的数据操作与List很相似.不同的是Opt ...

  8. 我的Machine Learning学习之路

    从2016年年初,开始用python写一个简单的爬虫,帮我收集一些数据. 6月份,开始学习Machine Learning的相关知识. 9月开始学习Spark和Scala. 现在想,整理一下思路. 先 ...

  9. ThoughtWorks.QRCode生成二维码

    首先引用需要的dll,此处使用的是ThoughtWorks.QRCode.dll,网上可以找到对应的,此处也有一份,点击下载 http://files.cnblogs.com/files/ives/T ...

  10. 怎样高效地去判断Array中是否包含某个值?

    问题 怎样去判断Array(无序)中是否包含某个值呢? 这是一个在Java中经常被问到的问题.它也是Stack Overflow上投票前几的一个问题.下面将展示投票前几的几个回答,这些回答使用不同的方 ...