Java: Best way to iterate through a Collection (here ArrayList)

Jason Rogers picture Jason Rogers · Mar 8, 2011 · Viewed 238.4k times · Source

Today I was happily coding away when I got to a piece of code I already used hundreds of times:

Iterating through a Collection (here ArrayList)

For some reason, I actually looked at the autocompletion options of Eclipse and it got me wondering:

What cases are the following loops better to use than the others?

The classic array index loop:

for (int i = 0; i < collection.length; i++) {
  type array_element = collection.get(index);
}

The Iterator hasNext()/next():

for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
  type type = (type) iterator.next();   
}

And my favorite because its so simple to write:

for (iterable_type iterable_element : collection) {

}

Answer

MAK picture MAK · Mar 8, 2011

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 ArrayLists, 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).