Collections: Iterators
Python |
Java |
An iterator is an object
that supports the traversal of a collection. The PVM automatically uses an iterator whenever it sees a for loop. The iter function expects an iterable collection as an argument and returns
an iterator object for that collection. Example: i = iter([1, 2,
3])
An iterator tracks a
current position pointer to an element in the collection. The iterator method next() advances this pointer and returns the most recently visited element. Example: print i.next(), i.next(), i.next() When next has returned the last element in the collection, any subsequent
call of next will raise a StopIteration
exception. When the programmer
is finished using an iterator, it should be closed by using the close() method. To traverse all of the
elements with an iterator, embed the call of next in a try/except statement, as follows: while True: try:
element = i.next() #
process element except StopIteration:
i.close()
break |
An iterator is an object
that supports the traversal of a collection. The compiler generates code that uses an iterator whenever
it sees an enhanced for loop. All collections
implement the Iterable interface.
This interface includes a single method, iterator(), which returns an iterator object. An iterator object
implements the Iterator interface.
This interface includes the methods next(), hastNext(), and remove(). Like collections,
iterators can be generic. Thus,
the generic collectionÕs element type must be specified when a variable of
type Iterator is declared. Example use: # Create a list
of strings List<String>
lyst = new ArrayList<String>(); # Add some
strings to lyst # Open an
iterator on lyst Iterator<String>
i = lyst.iterator(); # Print all the
strings in lyst using the iterator while
(i.hasNext()){ String s = i.next(); System.out.println(s); }
|