Given the following code snippet:
int[] arr = {1, 2, 3};
for (int i : arr)
System.out.println(i);
I have the following questions:
- How does the above for-each loop work?
- How do I get an iterator for an array in Java?
- Is the array converted to a list to get the iterator?
If you want an
Iteratorover an array, you could use one of the direct implementations out there instead of wrapping the array in aList. For example:Apache Commons Collections
ArrayIteratorOr, this one, if you’d like to use generics:
com.Ostermiller.util.ArrayIteratorNote that if you want to have an
Iteratorover primitive types, you can’t, because a primitive type can’t be a generic parameter. E.g., if you want anIterator<int>, you have to use anIterator<Integer>instead, which will result in a lot of autoboxing and -unboxing if that’s backed by anint[].