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.

最新文章

  1. ubuntu 14.04下spark简易安装
  2. Map的keySet和entrySet
  3. AJAX里,使用XML返回数据类型,实现简单下拉列表
  4. TD Rigging Demo Reel 性感美女绑定展示
  5. mysql组合索引顺序参考
  6. OpenCV学习(一)
  7. 关于oracle分页的一些想法
  8. css3 选择器的比较(一) -- 以字符串开头
  9. POJ2485——Highways
  10. Spring EL中的类操作符
  11. JAVA金额按比例分摊,零头处理
  12. httpd日志和日志轮替工具
  13. 使用SQL命令批量替换WordPress站点中图片的URL链接地址
  14. php 数组写入文件
  15. BZOJ1173 CDQ分治 笔记
  16. 钉钉自定义机器人 发送文本 换行 \n无效果
  17. 用R语言分析与预測员工离职
  18. Intellij IDEA快捷键与使用技巧一览表
  19. vw, vh视区覆盖和自适应图片
  20. adb shell按键操作(input keyevent)

热门文章

  1. Java 8的新并行API - 魅力与炫目背后
  2. Android SQLite的ORM接口实现(一)---findAll和find的实现
  3. dock基本使用
  4. DES算法详解
  5. SpringMVC核心——视图渲染(包含视图解析)问题
  6. 给你的博客加上“Fork me on Github”彩带
  7. Lucene-Analyzer
  8. MVC应用程序实现上传文件
  9. (二)Protobuf的C#使用
  10. 无法将类型为“System.Windows.Controls.SelectedItemCollection”的对象强制转换为类型“System.Collections.Generic.IList`1