Search code examples
javaiterator

What are the benefits of using an iterator in Java


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?


Solution

  • 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.