can anyone please specify to me what are the advantages of Enhanced for loop and Iterators in java +5 ?
It is more concise. Only problem is null checking.
for (String str : strs) { // make sure strs is not null here
// Do whatever
}
Less typing! Plus more help from the compiler
A cleaner syntax ! There is no difference from the performance perspective as this is just a convenience for a programmer.
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){
....
}
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.
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...