zoukankan      html  css  js  c++  java
  • 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

    1. Slight performance advantage over an ordinary for loop since it computes the limit of the array index only once.

       

    1. 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));

         

    2. 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

    1. 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.
    2. 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.
    3. 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.

  • 相关阅读:
    Office相关
    Eclipse常用设置
    Google logos 纪念电吉他大师莱斯·保罗(LesPaul)演示
    强烈推荐SQL Prompt 3.8,并发布SQL Prompt 3.8 ,SQL Refator 的xxx
    C#命令行编辑器csc.exe
    JSP中文乱码问题 页面经过过滤器后得到的是中文,但插入到MYSQL数据库却成了“?”为什么?
    (转贴)来谈谈SQL数据库中"简单的"SELECT TOP—可能有你从未注意到的细节
    C#Winform限制Textbox只能输入数字
    VPC2007虚拟机与主机的互连互通方法
    邮件会消亡是无稽之谈
  • 原文地址:https://www.cnblogs.com/haokaibo/p/prefer-for-each-loops-to-traditional-for-loops.html
Copyright © 2011-2022 走看看