Java Iterator vs Iterable – Why Iterator is Not an Iterable

iterableiteratorjava

Why does the Iterator interface not extend Iterable?

The iterator() method could simply return this.

Is it on purpose or just an oversight of Java's designers?

It would be convenient to be able to use a for-each loop with iterators like this:

for(Object o : someContainer.listSomeObjects()) {
    ....
}

where listSomeObjects() returns an iterator.

Best Answer

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.

Related Question