How does the enhanced for statement work for arrays, and how to get an iterator for an array?
If you want an Iterator
over an array, you could use one of the direct implementations out there instead of wrapping the array in a List
. For example:
Apache Commons Collections ArrayIterator
Or, this one, if you'd like to use generics:
com.Ostermiller.util.ArrayIterator
Note that if you want to have an Iterator
over primitive types, you can't, because a primitive type can't be a generic parameter. E.g., if you want an Iterator<int>
, you have to use an Iterator<Integer>
instead, which will result in a lot of autoboxing and -unboxing if that's backed by an int[]
.
No, there is no conversion. The JVM just iterates over the array using an index in the background.
Quote from Effective Java 2nd Ed., Item 46:
Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.
So you can't get an Iterator
for an array (unless of course by converting it to a List
first).
Arrays.asList(arr).iterator();
Or write your own, implementing ListIterator interface..
Google Guava Libraries collection provides such function:
Iterator<String> it = Iterators.forArray(array);
One should prefere Guava over the Apache Collection (which seems to be abandoned).
In Java 8:
Arrays.stream(arr).iterator();