Robert,
When all you have is "a List" then there is no question about it: use an Iterator. Because the List you have may be a LinkedList and get() will perform O(n), giving the entire loop O(n*n) performance. Ouch. An Ierator will give you O(n) performance on any flavour of List.
If, on the other hand, you know that your List is actually an ArrayList, it is tempting to use get() is a little bit faster.
Do not do this. You would be, deviously, implicitly, coding to implementation rather than interface. Increasing the coupling, and reducing the abstraction and flexibility in your code. If you really, really have to do this (remember the
first three rules of optimization though) then use get(), while at the same time changing variables and method signatures from List to ArrayList to clearly flag up that you are coding to a specific implementation here.
Finally, if you can't require an ArrayList, for example because you're developing a library and really can't make assumptions about the kind of List you're getting, yet you still need the fastest possible iteration, use
You may find the javadoc for java.util.RandomAccess interesting reading.
- Peter
[ February 02, 2003: Message edited by: Peter den Haan ]