传统循环和for循环之间有什么区别? [英] What is a difference between traditional loop and for-each loop?

查看:232
本文介绍了传统循环和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

      • in case of LinkedList in every iteration of the loop, get(i) will have to iterate over all elements starting from head/tail to i

      • i = 0; 而不是 int i = 0; - 将引用声明的变量在循环之前,可能的副作用在外面循环

      • > 而不是< - 循环不会执行

      • j ++ 而不是 i ++ - 无限循环

      • .get(j)而不是 .get(i) - 总会得到相同的元素

      • i = 0; instead of int i = 0; - will refer to variable declared before the loop, possible side effects outside of the loop
      • > instead of < - loop will not execute
      • j++ instead of i++ - 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 a Set - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆