Re: Iterators in Java and C++
On Apr 3, 11:22 pm, Razii <DONTwhatever...@hotmail.com> wrote:
On Thu, 3 Apr 2008 14:02:01 -0700 (PDT), James Kanze
<james.ka...@gmail.com> wrote:
Not that Java's iterators are perfect, either. The merge
access and incrementing---as did the USL iterators. By the
time Java was being developed, we'd already established that
this wasn't a good idea, so it's hard to understand why they
did it.
I am not sure what you mean but with with 1.5, the syntax
changed from
for(Iterator lineup = list.iterator() ; lineup.hasNext() ; ) {
Object thatThing = lineup.next();
And that's the problem. You should be able to access the object
without advancing the iterator. Most logically, advancing the
iterator should be the third part of the if.
The standard "pattern" is:
for ( Iterator iter( someInitializationArguments ) ;
! iter.isDone() ;
iter.next() ) {
doSomethingWith( iter.element() ) ;
}
In a well written iterator, doSomethingWith should encompass
deleting the element from the container, if the iterator is
based on a container. (IIRC, Java supports this; C++ definitely
doesn't.)
myMonster.eat(thatThing);
}
to
for(Object thatThing : list) {
myMonster.eat(thatThing);
}
Interesting. But isn't it just a cosmetic fix? Suppose that my
doSomethingWith, above, was actually to remove the element from
the underlying container, g.e.:
for ( Iterator i = list.iterator() ; list.hasNext() ; ) {
Object o = iter.next() ;
if ( condition( o ) ) {
iter.remove() ;
}
}
Try writing a filtering iterator in Java which supports that,
and you'll see why merging advance and access is a bad idea.
(Of course, from a design point of view, it's very ugly.
Separation of concerns should be an important guiding
principle.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34