[H-GEN] Which is better?
Andrae Muys
andrae at internode.on.net
Sun Apr 25 06:37:02 EDT 2004
Edwin Groothuis wrote:
> It depends on what you do with the myArray in the loop :-)
>
> If you don't modify it (size-wise), then the first one is best.
> If you do modify it (size-wise), then the second one is best.
>
Ummm, if you modify it's size, the first isn't worse, it's *wrong*.
> Also, using a for() loops vs a foreach() loop:
> for (index=0;index<myArray.length;index++) {
> data=myArray[i]
> ...
> }
Heh, who stole your spacebar?
for (i = 0; i < myArray.length; i++) {
data = myArray[i];
...
}
(Note the corrected indexing :).
> at the first one you can "skip" elements by increasing the index
> in the loop, the second one does all of them. I prefer the second
> notation (because it's cleaner with regarding to syntax), but it's
> less flexible.
>
The second is preferable yes. However the loops are equivalent, if only
because if you try mutating the loop-index *inside* the loop in my
code-base I'll have you strung up by your entrails while I try and think
of something sutiably nasty to reciprocate with.
If you want to go skipping over elements, define a suitable iterator,
iteration function, or just use continue like Gosling intended!
Andrae
P.S. It is a worthwhile experiment writing a small application with
nothing but final fields, parameters, and variables -- then to relax the
restrictions slowly (first allow non-final fields, then non-final
variables/parameters). It will teach you alot about OO programming, and
programming in general.
More information about the General
mailing list