android - java foreach比for好在哪里
迷茫
迷茫 2017-04-18 10:21:28
[Java讨论组]

java foreach比for好在哪里

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(7)
黄舟

foreach 实际上是调用的集合的迭代接口,迭代过程中集合处于锁定状态,不能追加和删除元素。所以,理论上速度会比较快一些。
for 每次都需要查看集合大小,同时其操作在多线程环境会产生数据不同步的问题。
如果在检索过程中,需要对集合进行追加,删除操作,建议使用for,同时应考虑多线程安全问题。

怪我咯

使用for还是foreach最终还是由数据结构决定,特别要注意链表一定要用foreach,否则会有严重的性能问题

伊谢尔伦

循环链表结构用foreach
循环数组结构用for

天蓬老师

foreach用于迭代器,有些集合类型的数据结构也可以用,比如set和Hashmap,这种情况下就不好用数字索引了。

大家讲道理
  1. 因为foreach完全隐藏了迭代器和索引变量,避免了混乱和出错的可能。
    特别是多重for循环嵌套,i j混用可能出现手误。

  2. 只要是实现了Iterable<E>接口的类都可以使用foreach

怪我咯

From Item 46 in Effective Java by Joshua Bloch :

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);
}

When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

伊谢尔伦

个人认为还是能用for 就用for

因为不知道什么时候会在循环体里面根据索引做修改,直接用for就省得以后再改了Orz

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号