您的位置:首页 > 编程语言 > Java开发

think in java笔记:for each 循环

2016-06-22 09:47 471 查看

think in java笔记:for each 循环

适用于:

1. array

2. iteratable object

什么时候应该用:

So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

译:所以什么时候你应该用for each循环呢?在任何你可以用它的地方就用。它真的美化了你的代码。但是很不幸,你不能在任何地方用它。试着想一下,比如说,expurgate方法(一个collection的remove方法)。这个方法需要使用iterator来移除当前的元素。for each隐藏掉了iterator,所以你不能调用remove方法。因此for each不能用来过滤。相似的来说,for each也不适用替换立标或数组元素的操作。最后,它还不适用于并行循环多个集合的操作。这些缺点设计者应该知道,从而可以实现一个简洁、简单的方式用于大部分的情况。

1. 不能删除元素

2. 不能替换元素

3. 不能并行循环
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: