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. [python]新手写爬虫v2.5(使用代理的异步爬虫)

    开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...

  2. Android 简单计算器源码....

    PS:今天算是闲着没事做了一个小型的计算器...顺便熟悉一下Android的布局,组件,以及时间监听的方法...就当是做了一个小小的练习吧...     顺便去对比了一下别人写的代码...有的使用到了 ...

  3. ASP.NET运行时详解 集成模式和经典模式

    遗留问题 在<ASP.NET运行时详解 生命周期入口分析>中遗留两个问题,包括Application的InitInternal方法执行细节.IIS6和II7经典模式请求管道管理类Appli ...

  4. css3中的zoom元素属性值测试

    在样式表里头看到zoom:1的设置,很是好奇就去找了一些资料发现关于这个的讲述还是比较少. 理论知识 语法: zoom:normal | <number> | <percentage ...

  5. vmware安装mac

    1.笔记本安装mac10.6 2.用VMware8,需要在mac.vmx中添加以下语句 guestOS = "darwin10"ich7m.present="TRUE&q ...

  6. JavaScript语言知识收藏

    接触Web开发也已经有一段时间了,对javascript的认识也比以前有了更加深入的认识了,所以觉得应该整理一下. 一.JavaScript不支持函数(方法)的重载,用一个例子证明如下: functi ...

  7. ajax回调函数Status问题

    function readyDo() {//            alert(xhr.readyState + "分" + xhr.Status);            if ...

  8. MVC中视图View向控制器传值的方法

    MVC中视图View向控制器传值的方法步骤如下: 1.index页面: 页面中只需要一个触发事件的按钮

  9. 运用Microsoft.DirectX.DirectSound和Microsoft.DirectX实现简单的录音功能

    1.首先要使用Microsoft.DirectX.DirectSound和Microsoft.DirectX这两个dll进行录音,需要先安装microsoft directx 9.0cz这个组件, 百 ...

  10. Titanium开发环境搭建第一个坑

    操作系统: Ubuntu 12.04 LTS AMD64 在Titanium Studio中,装Titanium CLI怎么都不能成功,到了一个进度,发现卡在那里,硬盘一直狂闪,发现在Studio的文 ...