Effective Java 46 Prefer for-each loops to traditional for loops
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
- Slight performance advantage over an ordinary for loop since it computes the limit of the array index only once.
- 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));
- 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
- 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.
- 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.
- 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的更多相关文章
- 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 ...
- Effective Java 35 Prefer annotations to naming patterns
Disadvantages of naming patterns Typographical errors may result in silent failures. There is no way ...
- Effective Java 53 Prefer interfaces to reflection
Disadvantage of reflection You lose all the benefits of compile-time type checking, including except ...
- 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 ...
- Effective Java 18 Prefer interfaces to abstract classes
Feature Interface Abstract class Defining a type that permits multiple implementations Y Y Permitted ...
- Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...
- Effective Java 25 Prefer lists to arrays
Difference Arrays Lists 1 Covariant Invariant 2 Reified at runtime Erased at run time 3 Runtime type ...
- 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 ...
- 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 ...
随机推荐
- .NET框架面向对象分层的个人想理
简单.层次清晰不要过度优化,接口这玩意儿就是个双刃剑,玩好了解藕,玩不好自找麻烦,好的代码永远都是傻瓜都能看懂的. 总结成以下几条: 公用层 代码公用并且与第三方DLL和业务逻辑无关的 独立出来 逻辑 ...
- Spring基础—— 泛型依赖注入
一.为了更加快捷的开发,为了更少的配置,特别是针对 Web 环境的开发,从 Spring 4.0 之后,Spring 引入了 泛型依赖注入. 二.泛型依赖注入:子类之间的依赖关系由其父类泛型以及父类之 ...
- 【助教】Java获取数据库数据展示
本文将给出一个最简单的Java查询数据库中一张表的数据并将查询结果展示在页面的例子. 实际上,我们要解决以下两个问题: Java与数据库交互(以JDBC为例) 数据展示在前台页面(以Servlet+J ...
- 内核移植和文件系统制作(4):UBIFS根文件系统制作总结
UBIFS文件系统简介: 无排序区块图像文件系统(UnsortedBlock Image File System, UBIFS)是用于固态硬盘存储设备上,并与LogFS相互竞争,作为JFFS2的后继文 ...
- javascript的封装实例
StringBuffer方法的js自定义封装: <!doctype html><html lang="en"> <head> <meta ...
- AJAX编程-封装ajax工具函数
即 Asynchronous [e'sɪŋkrənəs] Javascript And XML,AJAX 不是一门的新的语言,而是对现有技术的综合利用.本质是在HTTP协议的基础上以异步的方式与服务器 ...
- javascript宿主对象之window.history
window.historys属性允许我们操作同一个浏览器回话中的已访问页面,例如我们可以看到在这之前我们浏览页面的数量: window.history.length 由于隐私保护,我们无法获取这些页 ...
- RHEL7文件查找
本文介绍RHEL7下which.whereis.locate.find命令的使用,重点介绍find命令的使用 which 命令:which 作用:查找命令的执行文件路径 语法:which [选项] [ ...
- .NET破解之PDFdo转换器
无意中看到一个PDF转换器,叫PDFdo,看起了功能挺多的,于是想把它破了. 下载 官网:http://www.pdfdo.com/ 安装 安装后,只有一个exe应用程序,如果是.NET 程序应该有很 ...
- arcgis union 0x80040218
我利用ArcGis中的union工具将两张图层叠加时,系统总是提示失败,这是什么原因?希望高手能够解决这个问题.图片是系统提示,表示看不懂哪里出错了? 你必须使用数据管理-要素-修复几何,源数据存在不 ...