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

后端 未结 12 2496
遥遥无期
遥遥无期 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:22

    The enhanced for-loop offers the following main advantage:

    for (int i=0; i <= list.size(); i++)
    

    It eliminates the repeated calculation of list.size() on every iteration in the non-enhanced version above. This is a performance advantage that matters.

    Alternatively, you may calculate the size outside the loop as follows using an additional variable:

    int size = list.size();
    for (int i=0; i <= size; i++)
    

提交回复
热议问题