Re: Comparison of For/While Loop
Gordon Beaton wrote:
On Fri, 11 Apr 2008 09:20:23 -0400, Lew wrote:
That is not the only use case for the 'for' loop.
for ( Iterator iter = collection.iterator(); iter.hasNext(); ) { ... }
It's bounded, but can you tell me how many times that loop will iterate?
Based on the information provided, there is no indication that the
loop is bounded (other than your statement) since the elements of the
iterator aren't shown to be "consumed" anywhere.
Well, excuuuuuuuuse me! Impute an "Object ob = iter.next();" inside the loop
for me, will you please?
As if you couldn't have done that in the first place.
for ( Foo foo = new Foo(); checkForTermination(); foo = new Foo() )
{ ... }
How many times will this one iterate?
The second example is unbound and will iterate until
checkForTermination() is false.
I'm not sure what point you're trying to make here.
Like I said at least twice, my point is that there other use cases for a 'for'
loop. This was one of them.
I certainly did not imply that "for" can't be used in other ways, only
that it's a good rule to follow when choosing because of the meaning
it conveys to the reader of the program.
In this case, the meaning is that 'foo' is an important, loop-local variable.
Obviously "for" can always be used in place of "while" because it lets
you use an arbitrary boolean expression for the loop condition. That
doesn't mean it's a good idea to do so.
This was an illustration of one place where it would be a good idea.
--
Lew