java foreach比for好在哪里
因为foreach
完全隐藏了迭代器和索引变量,避免了混乱和出错的可能。
特别是多重for循环嵌套,i
j
混用可能出现手误。
只要是实现了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.
15 回答8.3k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
foreach 实际上是调用的集合的迭代接口,迭代过程中集合处于锁定状态,不能追加和删除元素。所以,理论上速度会比较快一些。
for 每次都需要查看集合大小,同时其操作在多线程环境会产生数据不同步的问题。
如果在检索过程中,需要对集合进行追加,删除操作,建议使用for,同时应考虑多线程安全问题。