What are the benefits of using an iterator in Java

Viewed 13225

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?

7 Answers

To be able to safely remove elements from the collection while iterating on it and avoid ConcurrentModificationException in case you need to remove elements from the loop while iterating on it

please refer to this question

Related