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. 不能并行循环
相关文章推荐
- Spring框架的设计理念于设计模式分析(一)
- Spring 3.X 中各JAR包的用途说明
- 深入Struts2
- JDBC与javaBean
- java常用第三方软件包
- java中对象的拷贝(克隆)
- Java Properties 文件的加载和配置管理
- Spring3博客(内含ppt和代码的github地址)
- java 使用elasticsearch 以及复杂查询语句构建
- 编程技巧系列(7)java中从控制台输入多行数据 按回车键输入空行结束
- SpringMVC 返回json
- java 获取系统时间,算时间差
- eclipse创建maven多模块项目(单个类似)
- java 中计算时间差
- Java WEB 开发环境
- Eclipse的SVN插件与本地客户端关联不上解决方案
- Java编程注意事项
- java程序性能优化
- 24种设计模式——代理模式
- 一致性hash算法java实现