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) {
}