I was taught that the "correct" way to iterate an ArrayList is to use an Iterator, rather than a "for" loop with a counter. But recently I came across the RandomAccess tagging interface; it suggests that a for loop with a counter may be faster for an ArrayList. Have a look at the API docs for ArrayList and RandomAccess.
Neither of the examples that Kaylee shows involves a for-loop with a counter.
If you are using Java 5 or newer and you don't need explicit access to the iterator, then the shortest and clearest way to iterate over a list is to use the new "for each" syntax:
In a Java 1.3 and 1.4 environment at work, I've recently started using Keylee's 2nd example style with a for loop and an iterator. I resisted for a while because I thought for loops so often used an int counter or index that it might confuse readers to do something else. I guess getting rid of a line of code and a variable scoped outside the loop finally won me over.
If you are using Java 5 or newer and you don't need explicit access to the iterator, then the shortest and clearest way to iterate over a list is to use the new "for each" syntax
True - it will be the shortest and clearest source code, which is important. I'd again guess that the compiled byte code will be still near to identical.
Post by:autobot
and POOF! You're gone! But look, this tiny ad is still here:
a bit of art, as a gift, that will fit in a stocking