Why is Java's Iterator not an Iterable?

Łukasz Bownik picture Łukasz Bownik · May 8, 2009 · Viewed 47.7k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · May 8, 2009

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.