传统循环和for循环之间有什么区别? [英] What is a difference between traditional loop and for-each loop?
本文介绍了传统循环和for循环之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道它们之间是否存在差异:
I wonder if there is a difference between these:
ArrayList<Example> list = new ArrayList<Example>
1 - )
for(int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
2 - )
for(Example example : list) {
example.doSomething();
}
如果没有哪个更常见或更有效?
If there is not any difference which one is more common or efficient?
推荐答案
传统循环
Traditional loop
for (int i = 0; i < list.size(); i++) {
list.get(i).doSomething();
}
- 允许修改列表,例如:
- 你可以在列表的末尾添加额外的元素,它也将通过
- 可以用来指代另一个相同大小的列表
- 可用于引用上一个/下一个元素
-
get(i)
将必须迭代从head / tail
开始到i $ c $的所有元素c>
- in case of
LinkedList
in every iteration of the loop,get(i)
will have to iterate over all elements starting fromhead/tail
toi
-
i = 0;
而不是int i = 0;
- 将引用声明的变量在循环之前,可能的副作用在外面循环 -
>
而不是<
- 循环不会执行 -
j ++
而不是i ++
- 无限循环 -
.get(j)
而不是.get(i)
- 总会得到相同的元素 i = 0;
instead ofint i = 0;
- will refer to variable declared before the loop, possible side effects outside of the loop>
instead of<
- loop will not executej++
instead ofi++
- infinite loop.get(j)
instead of.get(i)
- will always get the same element
for (Example example : list) { example.doSomething(); }
- 不允许修改清单
- 尝试这样做很可能会导致
ConcurrentModificationException
- does not allow to modify the list
- trying to do so will most likely result in
ConcurrentModificationException
- 你不能引用上一个/下一个元素
- 有效
LinkedList
- efficient in case of
LinkedList
- 你可以用a轻松替换
List
设置
- 无需更改所需的循环 - 您可以轻松替换自己的类,只需实现
Iterable
- you can easily replace
List
with aSet
- no changes to the loop required - you can easily replace with your own class, it just has to implement
Iterable
- 元素索引是必需的,或
- 列表必须修改
for-each
循环获胜,得分为3:2。for-each
loop wins with a score 3 : 2.使用传统循环的唯一原因是:
The only reason to use a traditional loop is when:
这篇关于传统循环和for循环之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- trying to do so will most likely result in
- 尝试这样做很可能会导致
查看全文