Re: Improved for each loop
On Mon, 13 Jul 2009, markspace wrote:
Lew wrote:
The variant that my hands want to type is:
Collection <Foo> foos = obtainSomehow();
for ( int ix = 0; Foo foo : foos; ++ix )
{
sparse.put( ix, foo );
}
That's an interesting idea. I wonder if for-each could be expanded to
include an Iterator too.
for( Interator<> i -> foos ) {
if( i.next().equals( badValue ) ) {
i.remove();
}
}
But this appears to have been deliberately excluded by the language
designers.
Not being able to for-loop over an Iterator, as opposed to an Iterable, is
also incredibly frustrating. I start with something like this:
for (String s: someCollectionOfStrings) {
fooBarDoStuff();
doSomethingOnlyForTheLastElement(); // needs a guard
}
And then i realsie that i can't do that - i have to rewrite the loop as a
while loop. Like:
Iterator<String> it = someCollectionOfStrings.iterator();
while (it.hasNext()) {
s = it.next()) {
fooBarDoStuff();
if (it.hasNext()) doSomethingOnlyForTheLastElement();
}
Which feels much less cohesive and more clunky to me.
If you want to use a traditional three-part for loop, you have to do
something bonkers like:
String s;
for (Iterator<String> it = someCollectionOfStrings.iterator(); it.hasNext() && ((s = it.next()) != null);) {
fooBarDoStuff();
if (it.hasNext()) doSomethingOnlyForTheLastElement();
}
Although if your collection contains nulls, you'll need to find a
different way of writing 'true' that has an assignment to s as a side
effect - you could just tack a || true on the end, i suppose. Or write
assignment to s twice, once at the start and once in the update clause.
I want to be able to do:
Iterator<String> it = someCollectionOfStrings.iterator()
for (String s: it) {
fooBarDoStuff();
if (it.hasNext()) doSomethingOnlyForTheLastElement();
}
tom
--
In other news, has anyone here read Blindness? Does it get better after
the 30 page mark, is does the whole thing read like a sentimental fairy
tale for particularly slow children? -- Abigail