You could use Arrays.asList
:
return Arrays.asList(items).iterator();
It simply wraps the array in a list implementation so that you can just call the iterator()
method on it.
Be aware that this approach will only works with array of objects. For primitive arrays you would have to implement your own iterator (with an anonymous class for instance).
As of Java 8, you could also use
Arrays.stream
to get an iterator out of the box (and make this code compiling also if
items
is an
int[]
,
double[]
or
long[]
):
return Arrays.stream(items).iterator();
though you won't be able for the primitive data types char
, float
and short
as there are no corresponding stream implementations. You could however use this workaround:
return IntStream.range(0, items.length).mapToObj(i -> items[i]).iterator();