-2

What is the use-case for Iterator and for loop (not for-each loop)

Please explain with example.

App Kart
  • 924
  • 2
  • 13
  • 24
  • What "old loop"? What use of "iterator"? Some small examples would help clarify the question. – user2864740 Dec 01 '13 at 08:35
  • simple for loop. for(int i ; i < n ; i++) – App Kart Dec 01 '13 at 08:36
  • Put that up in the post - edit it :) Also, is this only about the "old loop" or also the ["new enhanced loop"](http://www.cis.upenn.edu/~matuszek/General/JavaSyntax/enhanced-for-loops.html)? – user2864740 Dec 01 '13 at 08:36
  • my simple question is why itertor introduce in java – App Kart Dec 01 '13 at 08:39
  • 1
    Because it has a purpose. Imagine there is a Linked List. Would you *really* want to iterate it using the "old loop"? That would be very inefficient! Or what about a HashMap - how would one iterate that, since there are no [direct] indices? – user2864740 Dec 01 '13 at 08:40
  • We can also traverse collection classes from simple for each loop or simple loop. – App Kart Dec 01 '13 at 08:42
  • 2
    Iterable is specifically necessary to use a for-each loop. You can't use a for-each unless the class implements Iterable. – Radiodef Dec 01 '13 at 08:44
  • @user2864740 why do you think that iterating using an "old loop" is inefficient ? – Nir Alfasi Dec 01 '13 at 08:47
  • @alfasin Because iterating a `LinkedList` using an `Iterator` is linear time, and iterating using `get` is `n^2`. – chrylis -cautiouslyoptimistic- Dec 01 '13 at 08:50
  • @alfasin In the particular case of LinkedList using `get` has to traverse the entries to find the specified index. Very very inefficient. The iterator stores the next and last entries as fields. – Radiodef Dec 01 '13 at 08:50
  • Thanks for the answers guys. This is indeed a specific case where it's inefficient. An ArrayList is obviously not such a case. @user2864740 wrote it in such determination that I thought I'm missing something :) – Nir Alfasi Dec 01 '13 at 08:52

5 Answers5

3

Besides the fact that an iterator can check if there is a next element (hasNext()) before it fetches it - it can also remove an element from the collection. If you run in a loop and try to remove an element - what should be the "next" element ?

The Iterator interface (and its sub-interfaces) implementations provide an easy, safe, fail-fast unsynchronized mechanism to modify as well as iterate a collection. It saves the boilerplate of implementing it by yourself and provides an efficient and bug-free tool for the developer.

Foreach loop is implemented by iterator, so by using it you're not doing anything differently - it's a good tool when all you need is a simple "read only" iteration.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • In simplet terms, it was thoroughly tested before it was released hence lesser chances of bugs than traditional for.loop =] – An SO User Dec 01 '13 at 09:08
1

Don't you like simplicity ? What would you say when you are introduced to the topic of closures ? Would you shun it like you shun collection-based for loops ?

The more 'compact' the code is, the easier it becomes to understand and thus easier to maintain.

for(String each : anArrayList){
    // do something
}

for(int i = 0; i < anArrayList.size(); i++){
    // do something
}  

The first one uses an iterator while the second uses the more 'traditional' for loop. The intent of what the programmer wants to do becomes clearer in the first one. Plus, it is easier to understand.

Also, you don't just traverse, you can do a whole lot when iterating. Like remove an element from a collection, add it to another, perform computations on it and so on...

SSCCE:

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class AnIterator {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>(); 
        List<String> list2 = new ArrayList<>();

        list1.add("One");
        list1.add("Two");
        list1.add("Three");
        list1.add("Four");
        list1.add("Five");

        Iterator it = list1.iterator();
        while(it.hasNext()){
            String next = (String) it.next();
            String temp = next.toLowerCase();
            char x = temp.charAt(0);
            if(x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'){
                it.remove();
                list2.add(next);
            }
        }

        System.out.println("Vowels: " + list2);
        System.out.println("Consonants: " + list1);

    }
}  

The SSCCE shows how you can remove an element from a collection using an Iterator. is it easier to understand than traditional for loop ? =)

Contrast it with this:

for(int i = 0; i < list1.size(); i++){
            String element = list1.get(i);
            String temp = element.toLowerCase();

            // same logic goes here

}  

Iterator is more elegant ?

An SO User
  • 24,612
  • 35
  • 133
  • 221
1

If a class is iterable, then we know that we can get an iterator and use said iterator to navigate through the data structure. We don't need to know what the class looks like or how it works, etc. All we need to know are the methods for iterator.

Steve P.
  • 14,489
  • 8
  • 42
  • 72
1

Iterator can be used for example if you would like to remove items while traversing a collection. For loop is just a convenience to reduce code size and code readability if do not require any specific functions of iterator.

for(Iterator<Integer> iter = list.iterator(); iter.hasNext(); )
{
    int nextInt = iter.next();
    if(nextInt==0)
    {
        iter.remove();
    }
}
Alexey A.
  • 1,389
  • 1
  • 11
  • 20
  • can't remove element from loop while traversing? – App Kart Dec 01 '13 at 08:40
  • it depends on collection implementation, genearally it's considered safe to delete with iterator. – Alexey A. Dec 01 '13 at 08:43
  • 1
    It is not safe only in a multithreaded environment when one iterator modifies the structure of the collection while another iterator iterates it. Such a behavior will cause a ConcurrentModificationException – Nir Alfasi Dec 01 '13 at 08:45
1

As far as I know the foreach loop is using internal the iterator aswell.

This could also be interesting for you: Performance of traditional for loop vs Iterator/foreach in Java

Community
  • 1
  • 1
Ben
  • 1,157
  • 6
  • 11