Iterators (was: Re: [Tutor] text module)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 1 Sep 2002 14:04:38 -0700 (PDT)


On Sun, 1 Sep 2002, Erik Price wrote:

> "iterator protocol" makes me wonder if iterators are found in other
> programming languages other than Python.  Obviously it wouldn't use the
> double-underscore convention for the method to be subclassed, but is
> this something that's found in C++, Java, or Obj-C (etc)?


Java does have an Iterator protocol, but it's somewhat clunky.  If you're
really interested, take a look at:

http://developer.java.sun.com/developer/onlineTraining/collections/index.html

(In Java, using an iterator is considered an advanced topic.  *cough*)



Python's for loop is nice because it handles the iteration concept for us:

###
names = ['demonthenes', 'locke', 'antigone', 'socrates', 'plato']
for n in names:
    print n
###



Java, on the other hand, has no explicit support for the interface; and
all things need be done explicitely, using the methods of the Iteration
interface:

/*** Java ***/
// assume that 'import java.util.*;' has been written.

List names = new List(Arrays.asList
                          (new String[] { "demonthenes",
                                          "locke",
                                          "antigone",
                                          "socrates",
                                          "plato" }));
Iterator iter = names.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}
/******/

(I have not tested the above code; I hope I haven't made a typo!)


So, in Java, using the Iterator concept involves a little bit more work:
the idea is the same, but the execution is just a bit... well, it just
seems like explicit array indicing would be easier.  *grin*


Hope this helps!