java foreach比for好在哪里

java foreach比for好在哪里

阅读 6.4k
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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题