What are the Advantages of Enhanced for loop and Iterator in Java?

后端 未结 12 2417
遥遥无期
遥遥无期 2020-11-27 20:48

can anyone please specify to me what are the advantages of Enhanced for loop and Iterators in java +5 ?

相关标签:
12条回答
  • 2020-11-27 21:35

    It is more concise. Only problem is null checking.

    for (String str : strs) {  // make sure strs is not null here
        // Do whatever
    }
    
    0 讨论(0)
  • 2020-11-27 21:35

    Less typing! Plus more help from the compiler

    0 讨论(0)
  • 2020-11-27 21:36

    A cleaner syntax ! There is no difference from the performance perspective as this is just a convenience for a programmer.

    0 讨论(0)
  • 2020-11-27 21:42

    For me, it's clear, the main advantage is readability.

    for(Integer i : list){
       ....
    }
    

    is clearly better than something like

    for(int i=0; i < list.size(); ++i){
      ....
    }
    
    0 讨论(0)
  • 2020-11-27 21:44

    As others already answer, it is a syntax sugar for cleaner. If you compare to the class Iterator loop, you will found one less variable you will have to declare.

    0 讨论(0)
  • 2020-11-27 21:46

    Major drawback is the creation of an Iterator, which is not there with an index-based loop. It is usually OK, but in performance-critical sections (in a real-time application for instance, when it has to run several hundreds times a second), it can cause major GC intervention...

    0 讨论(0)
提交回复
热议问题