Iterator vs Loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • uthaman
    New Member
    • Sep 2007
    • 1

    Iterator vs Loop

    what is the difference between iterator and lops
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    Originally posted by uthaman
    what is the difference between iterator and lops
    An Iterator is an Object, which goes through a Collection (e.g. Vector, List, ...) and you can do something with whatever the Iterator is pointing at.

    A Loop is a construct, that repeats something for a certain amount of times.

    Iterators and Loops are often used together. What I guess you mean is: What's the difference between
    [CODE=java]
    Vector<String> vector = new Vector<String>( );
    vector.add("Hel lo");
    vector.add("Wor ld");

    for(int i=0; i<vector.size() ;i++)
    {
    System.out.prin tln(vector.elem entAt(i));
    }
    [/CODE]and[CODE=java]
    Vector<String> vector = new Vector<String>( );
    vector.add("Hel lo");
    vector.add("Wor ld");

    Iterator vectorIterator = vector.iterator ();
    while(vectorIte rator.hasNext() )
    {
    System.out.prin tln(vectorItera tor.next());
    }
    [/CODE](You can replace the Vector with another Collection.)

    One big advantage of the first option is, that you always know, at which position you are.

    One big advantage of the second option is, that you don't have to know the size of your Collection.

    I can't think of any further differences in the usage at the moment, but the concept is, as you see, quite different.

    Greetings,
    Nepomuk

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by uthaman
      what is the difference between iterator and lops
      If "lops" was supposed to be loop, then
      an Iterator is an interface that facilitates enumeration over a collection while a loop is a program construct that facilitates repetition in a program.

      P.S Changed thread title

      Comment

      Working...