can anyone please specify to me what are the advantages of Enhanced for loop and Iterators in java +5 ?
In for-each loop, we can't modify collection, it will throw a ConcurrentModificationException on the other hand with iterator we can modify collection. Modifying a collection simply means removing an element or changing content of an item stored in the collection.
A Java code to loop a List which containing 1, 5, 10 and 15 million records. The iterator loop is the slowest, and the difference between for loop and while loop isn't that significant.
The difference is largely syntactic sugar except that an Iterator can remove items from the Collection it is iterating. Technically, enhanced for loops allow you to loop over anything that's Iterable, which at a minimum includes both Collections and arrays.
6-3-4: What are some of the reasons you would use an enhanced for-each loop instead of a for loop? I: If you wish to access every element of an array. II: If you wish to modify elements of the array. III: If you wish to refer to elements through a variable name instead of an array index.
The strengths and also the weaknesses are pretty well summarized in Stephen Colebourne (Joda-Time, JSR-310, etc) Enhanced for each loop iteration control proposal to extend it in Java 7:
FEATURE SUMMARY:
Extends the Java 5 for-each loop to allow access to the loop index, whether this is the first or last iteration, and to remove the current item.
MAJOR ADVANTAGE
The for-each loop is almost certainly the most new popular feature from Java 5. It works because it increases the abstraction level - instead of having to express the low-level details of how to loop around a list or array (with an index or iterator), the developer simply states that they want to loop and the language takes care of the rest. However, all the benefit is lost as soon as the developer needs to access the index or to remove an item.
The original Java 5 for each work took a relatively conservative stance on a number of issues aiming to tackle the 80% case. However, loops are such a common form in coding that the remaining 20% that was not tackled represents a significant body of code.
The process of converting the loop back from the for each to be index or iterator based is painful. This is because the old loop style if significantly lower-level, is more verbose and less clear. It is also painful as most IDEs don't support this kind of 'de-refactoring'.
MAJOR BENEFIT:
A common coding idiom is expressed at a higher abstraction than at present. This aids readability and clarity.
...
To sum up, the enhanced for loop offers a concise higher level syntax to loop over a list or array which improves clarity and readability. However, it misses some parts: allowing to access the index loop or to remove an item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With