Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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.

1 Answer

0 votes
by (46k points)

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.

Related questions

0 votes
1 answer
asked Jul 20, 2019 in Java by Anvi (10.2k points)
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...