Héctor
Héctor

Reputation: 26034

Iterator of Object[]

Is there a way to obtain the iterator of an array? Something like that:

class MyCollection implements Iterable<String> {

   String[] items;

   @Override
   public Iterator<String> iterator() {
      return items.iterator(); //obviously, it doesn't compile.
   }

}

Upvotes: 0

Views: 189

Answers (2)

Alexis C.
Alexis C.

Reputation: 93842

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();

Upvotes: 7

user902383
user902383

Reputation: 8640

you could always define your own iterator

public class ArrayItterator<T> implements Iterator<T>{
    private final T[] array;
    int i = 0;
    public ArrayItterator(T[] array) {
        super();
        this.array = array;
    }

    @Override
    public boolean hasNext() { 
          return i<array.length;
    }

    @Override
    public T next() { 
          return array[i++];
    }

}

and then use it

@Override
   public Iterator<String> iterator() {
        return new ArrayIterator<String>(items);
   }

Upvotes: 1

Related Questions