Iterate without an index
来源:互联网 发布:同步看电视的软件 编辑:程序博客网 时间:2024/05/29 13:22
http://www.javapractices.com/topic/TopicAction.do?Id=88
Many programmers have a strong preference for using a for-each loop or an Iterator instead of a for-loop.
The traditional for-loop always uses an explicit loop index - an integer that identifies each iteration. The problem is that loop indexes have always been a fruitful source of error. For example, off-by-one errors are very common in programming, and they are often related to these loop indexes. In addition, the (somewhat unnatural) computer science tradition of starting loop indexes from 0 instead of 1 often contributes to these sorts of bugs.
Since they are more error prone, for-loops with indexes should generally be avoided, in favor of the more robust, compact, and elegant for-eachloop.
Example
import java.util.*;/** Different iteration styles. */public class IterateNoIndex { /** * Iterating without an index is more compact and less * error prone. */ public void withoutIndex(){ //for-each loop is usually preferred List<String> trees = Arrays.asList("Maple", "Birch", "Poplar"); for(String tree: trees){ log(tree); } //Iterators are not as compact as a for-each loop //but sometimes you need them: removing/replacing items, //and 'parallel' iterations across two data structures Iterator<String> iter = trees.iterator(); while (iter.hasNext()) { log(iter.next()); } } /** Iterating with an index is more error prone. */ public void withIndex(){ //traditional for-loop for(int idx=0; idx < 10; ++idx){ log("Iteration..." + idx); } } // PRIVATE private void log(String aMessage){ System.out.println(aMessage); }}
- Iterate without an index
- iterate
- createQuery without an active transaction
- what is an elasticsearch index?
- Oracle_create an index using unusable
- How to see index usage (without "alter index ... monitoring usage")
- Develop a web service without an IDE
- TWAIN协议(Toolkit Without An Interesting Name)
- Variances without ref to an item
- How to Learn Programming Without an Internet?
- Oracle 12C - Creating an Index Using Advanced Index Compression
- Creating an Index Table in STL
- Creating an Index Online
- Insert 100000 tuples with or without index on ML
- DML with or without Index on ML(use Random())
- DML with or without Index on SQLite(use Random())
- HTTP/HTTPS, without index.php, using htaccess, plus XHR
- Generating an SSL certificate on Windows without IIS
- 经典排序算法之——快速排序
- Encapsulate collections
- cocos2d:如何优雅的管理游戏资源
- windows7打开chm文件,不显示内容的解决
- Java并发基础构建模块简介
- Iterate without an index
- typedef的用法总结
- String 对象 与 StringBuilder 对象的比较.....
- 在Oracle库上几种特殊情况的SQL语句
- Java的正则表达式的基本语法(不全)
- socket通信之可靠和不可靠的原理
- Android的网络与通信
- Java正则表达式入门
- 二、总结几种关于ViewControllers之间传值的方式(从子视图向父视图传值)