3

Possible Duplicates:
What are the Advantages of Enhanced for loop and Iterator in Java ?
Is there a performance difference between a for loop and a for-each loop?

Below code shows that with both for loop as well as with iterator we can iterate the elements of collection then what is the difference between for loop and iterator and why we should use only iterator in case of collection

    ArrayList<String> list=new ArrayList<String>();
    list.add("dipu");
    list.add("alok");
    list.add("alok");
    list.add("jyoti");
    ArrayList<Integer> al=new ArrayList<Integer>();
    al.add(1);
    al.add(2);
    String a[]={"a","b"};
    for(int i=0;i<list.size();i++)
    {
        System.out.println(list.get(i));;
    }
    for(Integer t:al)
    {
        System.out.println(t);
    }
    for (Iterator iter = list.iterator(); iter.hasNext();)
        {
        System.out.println(iter.next());
        }
    Iterator it=list.iterator();
    while(it.hasNext())
    {
    String st=it.next().toString();
    System.out.println(st);
    }
Community
  • 1
  • 1
user686303
  • 31
  • 1
  • 1
  • 2
  • Enhanced for loops are a little faster than normal for loops for accessing elements normally, but not with array based collections since they can immediately access an index with ease – Kurru Mar 31 '11 at 18:50

4 Answers4

2

Though I'm not familiar with the Java Iterator, it seems very similar to .NET's IEnumerable.

The advantages of the enumerator/iterator are:

  • You don't have to know the size of the collection, which in some cases can require N steps to determine, increasing execution time (though it remains technically linear). Instead, you just keep moving to the next element until there aren't any.

  • Because the cardinality of the collection doesn't have to be known, iterators can allow collections to be generated dynamically, or "streamed" with elements being added while you begin work on what you already have. For instance, you could derive from Iterator and/or overload iterator getters to create classes that generate finite or infinite series "lazily", figuring out what each element in your enumerable collection is when you ask for it instead of when you define the collection. You could also set up a buffered stream, where you process records, packets, etc that you have received, while another thread or process works ahead of you to queue up more for you to work on.

  • Any collection that can provide an iterator can be traversed in exactly the same way, instead of having to know whether it's indexable, what the method or member is that defines size, etc etc etc. Iterator implementations thus provide an adapter to allow the same code to work on any collection passed to it.

  • Does Java have an equivalent to .NET extension methods (static methods that are not part of the class definition, but that work on instances of the type and can be called as if they were instance methods)? If so, you can define methods that take an Iterator and produce a result, which could be another Iterator. .NET's Linq library is based heavily on these, providing a very powerful collection-manipulation framework allowing for common operations to be chained together, each operating on the result of the previous operation.

KeithS
  • 70,210
  • 21
  • 112
  • 164
1

Iterators are just generally safer I would say, no risk of accessing an index that isn't there. They also have a little more flexibility since you can go backwards and forwards with them whereas for loops only go one way and in many languages you cannot alter the value of the loop index within the loop (i.e. you cannot change the increment rate).

They are also the ONLY way to remove items from a collection while iterating through them. Removing an item from a collection while you were in a for loop through it would be disastrous and is generally not even allowed by Java, I forget what the exception is, but I've got one for doing that before.

Think about it, once you remove the item all the other ones shift down. Meanwhile on your next iteration your index was still incremented meaning 2 things.

First is that you will skip whatever the next element is as it was shifted to the position you just deleted from.

Second is that your loop will extend beyond the size of the collection which you have now altered.

gnomed
  • 5,483
  • 2
  • 26
  • 28
  • I haven't tried this in Java, but I know you can modify arrays from a for loop in other languages. As long as you increment/decrement your index variable for item you insert/remove, and recalculate the length of the array on each loop iteration, you won't have any problems – Sam Dufel Mar 31 '11 at 18:42
  • You can edit the list in a normal for loop. NOT in an iterator. They normally fail if you remove an item from a list – Kurru Mar 31 '11 at 18:49
  • @Sam Dufel - I believe the question was in reference to collections and not arrays which are very different. @Kurru - What? Iterators have a `remove()` method which removes the element that was returned by the most recent `next()` call. I highly doubt the iterator would fail if you used it seeing as it is provided.... And maybe you can edit/remove from the collection in a normal for loop, but why would you want to when you can do it more safely? – gnomed Apr 01 '11 at 16:33
1

I try to explain it with two short sentences:

  • With the enhanced for loop its easier to loop over it (more human readable..)
  • With the iterators it is possible to modify the list during the iteration, which is with the other methods not possible
Prine
  • 12,192
  • 8
  • 40
  • 59
0

The 'stream' you're iterating on might not even be indexable. That is, the iterator makes possible a very convenient 'lazy-evaluation' pattern where data isn't even loaded/constructed until the iterator asks for it. This is wonderful for repositories and database access, as well as networking.

n8wrl
  • 19,439
  • 4
  • 63
  • 103