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?