Why is Java's Iterator not an Iterable?
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.
Solution 1:
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.
Solution 2:
Because an iterator generally points to a single instance in a collection. Iterable implies that one may obtain an iterator from an object to traverse over its elements - and there's no need to iterate over a single instance, which is what an iterator represents.