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

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

    As others said, the enhanced for loop provides cleaner syntax, readable code and less type.

    Plus, it avoids the possible 'index out of bound' error scenario too. For example, when you iterate a list manually, you might use the index variable in a wrong way, like:

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

    which will throw exception. But incase of enhanced for loop, we are leaving the iterating task to the compiler. It completely avoids the error case.

提交回复
热议问题