Why is Java’s Iterator not an Iterable?

An iterator is stateful. The idea is that if you call Iterable.iterator() twice you’ll get independent iterators – for most iterables, anyway. That clearly wouldn’t be the case in your scenario.

For example, I can usually write:

public void iterateOver(Iterable<String> strings)
{
    for (String x : strings)
    {
         System.out.println(x);
    }
    for (String x : strings)
    {
         System.out.println(x);
    }
}

That should print the collection twice – but with your scheme the second loop would always terminate instantly.

Leave a Comment