What are the benefits of using an iterator in Java

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)

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.


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.

Tags:

Java

Iterator