Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of using an iterator in Java

Tags:

java

iterator

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?

like image 638
chronical Avatar asked Aug 29 '10 17:08

chronical


People also ask

What is the benefit of adding an iterator to the list class?

By using Iterator, we can perform both read and remove operations. Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface.

What is the advantage of using iterators over simple for loop?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.

What is the purpose of iterator interface?

The Iterator interface of the Java collections framework allows us to access elements of a collection. It has a subinterface ListIterator . All the Java collections include an iterator() method. This method returns an instance of iterator used to iterate over elements of collections.


1 Answers

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)
like image 129
sinuhepop Avatar answered Sep 28 '22 02:09

sinuhepop