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 ...
随机推荐
- CSS程序思想
CSS的设计思想,比如:CSS预处理器.CSS对像(OOCSS).SMACSS.Atomic设计和OrganicCSS等 一.CSS预处理器最重要的功能: 1.连接: ...
- [团队项目]sprint3 & 团队贡献分
希望各组认真准备,拿出最好的阵容最好的状态,展示一学期的学习与工作成果. 各组注意完成sprint3的博客,写上团队贡献分. 将演示PPT(如果有)和代码上传到github. 截止日期:2016.6. ...
- Websocket 概述
WebSocket protocol 是HTML5一种新的协议.它实现了浏览器与服务器全双工通信(full-duplex). [[ from websocket是什么原理? ]] 一.WebSocke ...
- Unity Shader入门基础(一)
渲染流水线 一.渲染流水线 渲染流水线的工作任务在于由一个三维场景出发.生存(或者说渲染)一张二维图像.换句话说,计算机需要从一系列的顶点数据.纹理等信息出发,把这些信息最终转换成一张人眼可以看到 ...
- Mysql主从备份和SQL语句的备份
MySQL服务器的主从配置,本来是一件很简单的事情,无奈不是从零开始,总是在别人已经安装好的mysql服务器之上 ,这就会牵扯到,mysql的版本,启动文件,等一些问题. http://www.cnb ...
- yyyy/M/d h:m:s 转换成 yyyy-MM-dd hh:mm:ss
var arrTime = (dtime).replace("/", "-").replace("/", "-"); v ...
- 从零开始学习Linux(mkdir and rmdir)
今天说mkdir 和 rmdir.因为mkdir 内容比较少.而且也很好理解. 对于mkdir来说,一般只用到 -p -m,我只用过-p参数,-m也是刚刚看的. 先说不带参数的: mkdir tes ...
- ahjesus让nodejs支持dotjs模板
经过几天的实验加搜索,终于知道一个中间件可以解决这个问题了 npm install consolidate consolidate传送门 传送门2使用说明传送门快照:ahjesus Since doT ...
- 硅谷新闻4--解决页签手指按下从左到右滑动的bug
有一种方法可以阻止父层的View截获touch事件,就是调用 getParent().requestDisallowInterceptTouchEvent(true);方法.一旦底层View收到tou ...
- inner Join on 随随随随随便一记
幼儿园大班生(随便的记一记) JOIN 分为:内连接(INNER JOIN).外连接(OUTER JOIN).其中,外连接分为:左外连接( ...