Dimitri Maziuk wrote On 12/20/05 12:20,:
Hendrik Maryns sez:
[ iterators ]
start your iteration again, for example, in (Hash)Set, there is no order
guarantee at all. But as indeed they are only a lightweight wrapper of
indexes, and with what I read about the differences in object creating
between Java and C++, I can see why they left this out.
Errm, they aren't lightweight wrappers for indexes. Recall that
Java has no separate RandomAccess and SequentialAccess lists,
there's only one List and it's implicitly sequential access.
There is only one java.util.List, but there's no implication
of an access pattern. Various methods of List take a position
argument, and there is no requirement or even suggestion that
successive calls to the methods should use adjacent indices.
True, some particular implementations of List cannot provide
efficient random access -- but that's not a characteristic of
List, but of (for example) LinkedList. Implementations like
ArrayList most definitely do support efficient random access.
Which means that rewinding an iterator is O(n) -- creating a
new one will be much faster in most cases.
Even a half-clever programmer can do better than that. If
there's an efficient way to start a brand-new Iterator at the
beginning of the List, a hypothetical Iterator.rewind() method
could use it.
Also, every index-based access is O(n), giving you O(n) for
for( Iterator i = l.iterator(); i.hasNext(); )
e = i.next();
and O(n^2) for
for( int i = 0; i < l.size(); i++ )
e = l.get( i );
True for LinkedList, but not true for ArrayList or Vector.
What's beyond me is why they didn't make Iterator.next()
return a boolean or void, and Iterator.get() for getting
to the element:
Ah, but "they" did exactly what you ask! They used
different names: hasNext() for your next() and next() for
your get(), but the same[*] functionality is provided.
Is it just the choice of names that bothers you?
[*] "The same" for "return a boolean." I confess I
do not understand what you mean by "return a [...] void,"
since the only use of `void' in Java is to indicate that
a method returns nothing at all, not ever.
either
while( i.next() )
or
for( Iterator i = l.iterator(); i.hasNext(); i.next() )
would be much better than what we have now.
The first is "what we have now," with a change of name.
The second is *exactly* "what we have how," so I don't see
how it "would be much better" than what it already is ...?