0

I have a class looking something like the code below. It implements the Iterable<T> iterface, which it uses to provide iteration capabilities over its contained array.

I have been in the habit of rolling my own trivial iterator to iterate over arrays. I just realized, however, that at least for spliterators, you can get an acceptable default implementation by calling Arrays.spliterator(array). Is there a similar default implementation of an ordinary Iterator<T> over an array of T?

public class MyClass implements Iterable<ContainedClass>
{
    ...
    private final ContainedClass[] array;
    ...

    //
    // INTERFACE: Iterable<ContainedClass>
    //

    @Override
    public Iterator<ContainedClass> iterator() {
        return ??? // I want to return a default implementation, not my own!
    }

    @Override
    public Spliterator<ContainedClass> spliterator() {
        return Arrays.spliterator(array);
    }
}
0xbe5077ed
  • 4,565
  • 6
  • 35
  • 77

2 Answers2

5

Closest thing to a default implementation in the JDK:

Arrays.asList(array).iterator()

Simple custom implementation:

public final class ArrayIterator<E> implements Iterator<E> {
    private final E[] _elements;
    private int _index;

    @SafeVarargs
    public ArrayIterator(final E... elements) {
        _elements = Objects.requireNonNull(elements);
    }

    public boolean hasNext() {
        return _index < _elements.length;
    }

    public E next() {
        if (hasNext()) {
            return _elements[_index++];
        }
        throw new NoSuchElementException();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}
Mike Strobel
  • 25,075
  • 57
  • 69
0

As already pointed out, you can simply use Arrays.asList(array).iterator() to create an array iterator. The temporary list is a lightweight wrapper and is nothing to worry about.

Alternatively you can use Arrays.stream(array).iterator(); which is equivalent. The advantage of using Arrays.stream(array) instead of Arrays.asList(array) is that there is the overload Arrays.stream(T[] array, int startInclusive, int endExclusive) similar to Arrays.spliterator so there is no big change if you ever need to process a range of the array.

Community
  • 1
  • 1
Holger
  • 285,553
  • 42
  • 434
  • 765