can anyone please specify to me what are the advantages of Enhanced for loop and Iterators in java +5 ?
You can iterate over any collection that's Iterable and also arrays. And the performance difference isn't anything you should be worried about at all.
Readability is important.
Prefer this
for (String s : listofStrings)
{
...
}
over
for (Iterator iter = listofStrings.iterator(); iter.hasNext(); )
{
String s = iter.next();
...
}
Note that if you need to delete elements as you iterate, you need to use Iterator.
For example,
List list = getMyListofStrings();
for (Iterator iter = list.iterator(); iter.hasNext(); )
{
String s = iter.next();
if (someCondition) {
iter.remove();
}
}
You can't use for(String s : myList) to delete an element in the list.
Also note that when iterating through an array, foreach (or enhanced for) can be used only to obtain the elements, you can't modify the elements in the array.
For more info, see this.