Java: Best way to iterate through a Collection (here ArrayList)
The first one is useful when you need the index of the element as well. This is basically equivalent to the other two variants for ArrayList
s, but will be really slow if you use a LinkedList
.
The second one is useful when you don't need the index of the element but might need to remove the elements as you iterate. But this has the disadvantage of being a little too verbose IMO.
The third version is my preferred choice as well. It is short and works for all cases where you do not need any indexes or the underlying iterator (i.e. you are only accessing elements, not removing them or modifying the Collection
in any way - which is the most common case).
All of them have there own uses:
If you have an iterable and need to traverse unconditionally to all of them:
for (iterable_type iterable_element : collection)
If you have an iterable but need to conditionally traverse:
for (Iterator iterator = collection.iterator(); iterator.hasNext();)
If data-structure does not implement iterable:
for (int i = 0; i < collection.length; i++)