I was browsing over the following code example:
public class GenericTest {
public static void main (String[] args) {
ArrayList<String> myList = new ArrayList<String>();
String s1 = "one";
String s2 = "two";
String s3 = "three";
myList.add(s1); myList.add(s2); myList.add(s3);
Iterator<String> itr = myList.iterator();
String st;
while (itr.hasNext()) {
st = itr.next();
System.out.println(st);
}
}
}
I’m wondering what are the benefits of using an implementation of the Iterator interface instead of using a plain-old for-each loop?
for (String str : myList) {
System.out.println(str);
}
If this example is not relevant, what would be a good situation when we should use the Iterator?
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
But sometimes the
hasNext()method of the “plain old” Iterator is very useful to check if there are more elements for the iterator.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 traversalit.next()andit.previous().So, they are not equivalent. Both are needed.