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) { }
The iterator can be used to iterate through the ArrayList wherein the iterator is the implementation of the Iterator interface. Some of the important methods declared by the Iterator interface are hasNext() and next().
HashMap ( HashSet uses HashMap<E,Object> ) isn't designed for iterating all items. The fastest way to iterate over HashMap is a combination of Iterator and the C style for loop, because JVM doesn't have to call hasNext() .
We can iterate on Java ArrayList using foreach loop introduced in Java 5, by far most clean method until you don't need to remove elements from ArrayList in that case you must use Java Iterator for looping or iterating over 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++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With