I was browsing over the following code example:
public class GenericTest {
public static void main (String[] args) {
ArrayList myList = ne
Basically, foreach loop is a shortcut for the most common use of an iterator. This is, iterate through all elements. But there are some differences:
The For-Each Loop was introduced with Java 5, so it's not so "old".
If you only want to iterate a collection you should use the for each loop
for (String str : myList) {
System.out.println(str);
}
But sometimes the hasNext()
method of the "plain old" Iterator is very useful to check if there are more elements for the iterator.
for (Iterator<String> it = myList.iterator(); it.hasNext(); ) {
String str = it.next();
System.out.print(str);
if (it.hasNext()) {
System.out.print(";");
}
}
You can also call it.remove()
to remove the most recent element that was returned by next.
And there is the ListIterator<E>
which provides two-way traversal it.next()
and it.previous()
.
So, they are not equivalent. Both are needed.
An iterator is an abstraction over how a collection is implemented. It lets you go over the whole collection one item at a time, optionally removing items.
The disadvantage of an Iterator is that it can be a lot slow if you DO know the underlying implementation. For example using an Iterator for an ArrayList is considerable slower than just calling ArrayList.get(i) for each element. Whether this matters much depends on what the code is doing.
I don't think there is any performance benefit in using either in most of cases if you are just iterating over collection/array. But usage may differ as per your use case.
for ( String str : myList ) { System.out.println(str); }
this code will actually use myList.Iterator to iterator over the list.
the new for
loop added since java 5 to make iteration over the collections and arrays easier.
by Iterator each implementation in Java Collection can have its own way of iteration (List, Set, LinkedList, Map or ....)
you can implement this interface in your custom classes as well. to let other code iterator over the elements that you have inside your object.
The two are equivalent in operation and performance in almost all cases. The only difference is that Iterators are supported on old versions of the Java JVM while the new "for" syntax was only introduced in JSDK 1.5 ("Java 5"), and some folks want to remain compatible with 1.4 or earlier.