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 ...
随机推荐
- 我也想聊聊 OAuth 2.0 —— 基本概念
这是一篇待在草稿箱半年之久的文章 连我自己都不知道我的草稿箱有多少未发布的文章了.这应该是我在上一家公司未解散之前写的,记得当时是要做一个开发者中心,很不幸. 今天,打开草稿箱有种莫名的伤感,看到这个 ...
- 让 ASP.NET JS验证和服务端的 双验证 更简单
只用JavaScript验证安全不安全谁都知道,答案是不安全,非常的不安全.因为在客户端进行的验证相当于“让用户自己验证自己”,很明显是不靠谱的.你不能避免一些恶意用户人为的修改自己的表单进行欺骗,也 ...
- 反射动态创建不同的Processor
1. 定义抽象方法 public abstract class BaseProcesser { public abstract void GetCustomerReportCard ...
- 【Android】记录反编译安卓程序步骤
主要是为了分析一个 App 里面用到的接口,以后移植 UWP 用. 1.http://jd.benow.ca/ 下载 JD-GUI. 2.https://github.com/pxb1988/dex2 ...
- Winform开发框架之客户关系管理系统(CRM)的报价单和销售单的处理
在前面介绍了很多CRM相关的界面和实现思路的随笔文章,本篇继续介绍一下系统中用到的一些经验和技巧片段.本篇随笔主要介绍客户关系管理系统(CRM)的报价单和销售单的处理界面效果,使用列表内置的选择代替弹 ...
- sql date()函数,时间格式
(1).GETDATE() 函数从 SQL Server 返回当前的日期和时间. 语法 GETDATE() 实例 下面是 SELECT 语句: SELECT GETDATE() AS CurrentD ...
- 【循序渐进学Python】11.常用标准库
安装完Python之后,我们也同时获得了强大的Python标准库,通过使用这些标准库可以为我们节省大量的时间.这里是一些常用标准库的简单说明.更多的标准库的说明,可以参考Python文档 sys 模块 ...
- 详细介绍ASP.NET页面间数据传递的使用方法
源码:http://www.jinhusns.com/Products/Download/?type=xcj 在ASP.NET中,页面间数据传递的方法有很多.下面为大家总结一下,页面间数据传递的方法. ...
- Yii2学习笔记之场景
场景 一个模型可能在多个场景中使用,在不同的场景中,模型可能使用不同的业务逻辑和规则.例如, User 模型可能在用户登录时使用,也可能在用户注册时使用,某些属性可能在用户注册时强制要求有,在用户登录 ...
- jsp中自定义Taglib案例
一.使用TagSupport类案例解析 1.自定义Tag使用jdbc连接mysql数据库 1.1定义标签处理器类 package com.able.tag; import java.sql.Conne ...