Thursday, August 3, 2006 10:25 AM
Use an iterator in the above example since that's what they're for.
Using an iterator makes no assumption on the random-accessibility of your collection. Therefore you could replace the list in your code by another random Collection without a sweat.
Also, although the performance of an ArrayList is pretty good for random-access (get(i)), for a LinkedList, the get(i) method becomes relatively expensive.
One more thing: if you know the size doesn't in the middle of your iteration, it is not advised to re-call size() in each iteration! Iterators throw appropriate exceptions for concurrent modifications as well.