`
leonzhx
  • 浏览: 796611 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 46: Prefer for-each loops to traditional for loops

阅读更多

1.  The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

 

2.  Not only does the for-each loop let you iterate over collections and arrays, it lets you iterate over any object that implements the Iterable interface. If you are writing a type that represents a group of elements, have it implement Iterable even if you choose not to have it implement Collection. This will allow your users to iterate over your type using the for-each loop.

 

3.  There are 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.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics