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. C# 获取磁盘空间大小的方法

    方法一:利用System.IO.DriveInfo.GetDrives方法来获取 /// /// 获取指定驱动器的空间总大小(单位为B) /// /// 只需输入代表驱动器的字母即可 (大写) /// ...

  2. 转载:第五弹!全球首个微信小程序(应用号)开发教程!通宵吐血赶稿,每日更新!

    博卡君今天继续更新,忙了一天,终于有时间开工写教程.不罗嗦了,今天我们来看看如何实现一些前端的功能和效果. 第八章:微信小程序分组开发与左滑功能实现 先来看看今天的整体思路: 进入分组管理页面--&g ...

  3. Spring基础——一个简单的例子

    一.学习版本 spring-framework-4.0.0 二.导入 jar 包: 三.在类路径下创建 Spring Config 文件:ApplicationContext.xml <?xml ...

  4. 6/20 sprint3 看板和燃尽图的更新

  5. Python打包-py2exe使用

    Py2exe 64位下载地址:http://download.csdn.net/detail/henujyj/8532827 Py2exe 32位下载地址:https://sourceforge.ne ...

  6. ASP.NET WebAPI 07 路由

    WebAPI的中路由设计与ASP.NET相似,但又是独立的一套框架. HttpRoute HttpRoute主要提供了路由模板,用于匹配url,生成virtualPath. public interf ...

  7. Java中Scanner类和BufferReader类之间的区别

    java.util.Scanner类是一个简单的文本扫描类,它可以解析基本数据类型和字符串.它本质上是使用正则表达式去读取不同的数据类型. Java.io.BufferedReader类为了能够高效的 ...

  8. AutoMapper映射ExpressionTree

    问题描述 项目中使用AutoMapper进行VO&DTO&Entity的互相映射,但是默认Map方法不支持Expression的转换.如 Expression<Func<E ...

  9. apple store链接格式文档

    备份一下: The app on Appstore has specific URL format http://itunes.apple.com/[country-code]/app/[app-na ...

  10. JavaScript中的null与nudefined

    null和undefined 概述 null与undefined都可以表示"没有",含义非常相似.将一个变量赋值为undefined或null,老实说,语法效果几乎没区别. var ...