19

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
chronical
  • 235
  • 1
  • 2
  • 6
  • 6
    For one thing, the for-each loop is neither plain nor old: it was officially introduced as the "enhanced for loop" in Java 5. – Michael Borgwardt Aug 29 '10 at 17:49
  • 1
    possible duplicate of [What are the benefits of the Iterator interface in Java?](http://stackoverflow.com/questions/89891/what-are-the-benefits-of-the-iterator-interface-in-java) – BalusC Aug 29 '10 at 17:58

7 Answers7

26

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:

  • You can iterate through an array using foreach loop directly
  • You can remove objects using an iterator, but you can't do it with a foreach loop
  • Sometimes is useful to pass an iterator to a function (specially recursive ones)
sinuhepop
  • 20,010
  • 17
  • 72
  • 107
12

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.

Soundlink
  • 3,915
  • 2
  • 28
  • 36
4

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.

  • If your case is only iterating over list, use of for each loop should be prefered since Java 1.5.
  • But if your case is manipulating collection while iterating You need to use Iterator interface.
JohnK
  • 6,865
  • 8
  • 49
  • 75
YoK
  • 14,329
  • 4
  • 49
  • 67
3
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.

mhshams
  • 16,384
  • 17
  • 55
  • 65
3

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.

locka
  • 5,809
  • 3
  • 33
  • 38
1

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.

samkass
  • 5,774
  • 2
  • 21
  • 25
1

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

osama yaccoub
  • 1,884
  • 2
  • 17
  • 47