think in java笔记:for each 循环

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. 不能并行循环

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值