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 ...
随机推荐
- IT168关于敏捷开发采访
1.我们知道敏捷开发是一套流程和方法的持续改进,通过快速迭代的方式交付产品,从而控制和降低成本.但是在实行敏捷初期,往往看不到很好的效果.这里面,您觉得问题主要出在哪?团队应如何去解决问题?金根:我认 ...
- C# 通过Get、Post、Soap调用WebService的方法
实现代码来源于网络,我只是作了一些修改! using System; using System.Web; using System.Xml; using System.Collections; usi ...
- struts2基础——请求与响应、获取web资源
一.请求与响应 Action1.含义:(1) struts.xml 中的 action 元素,也指 from 表单的 action 属性,总之代表一个 struts2 请求.(2) 用于处理 Stru ...
- ok6410 android driver(6)
This is a short essay about the mistakes in compiling ok6410 android-2.3 source codes. If there is n ...
- 可以调整gif动画图片尺寸的很实用的php类
类的使用demo: <?php //http://www.cnblogs.com/roucheng/ require_once "roucheng.php"; $gr = n ...
- C#函数、参数数组(例子)★
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- win32程序启用控制台
#include <cstdio> #define USE_WIN32_CONSOLE int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _I ...
- fibonacci数列的和取余(2)
Maybe ACMers of HIT are always fond of fibonacci numbers, because it is so beautiful. Don't you thin ...
- No.001:Two Sum
问题: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- javaweb学习之Servlet开发(二)
javaweb学习总结(六)--Servlet开发(二) 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个< ...