My buddy told me (but wasn't positive about it) that you can substitute a 'for each' loop wherever you would use the Iterator class. Is this true? If it's not, then could someone explain the purpose and use of the Iterator class? Thanks so much.
The enhanced for statement ("for-each") can be used either with an array or with any container that implements the Iterable interface. (See JLS 14.14.2 The enhanced for statement.) In fact, for Iterable containers, the for-each loop uses an Iterator behind the scenes.
But I wouldn't say that a for-each loop can be "substituted" wherever an Iterator is used, because an Iterator usually has more functionality than what's required in a for-each loop. For an idea of what else an Iterator might do, see the API documentation for Iterator and ListIterator.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Originally posted by marc weber: The enhanced for statement ("for-each") can be used either with an array or with any container that implements the Iterable interface. (See JLS 14.14.2 The enhanced for statement.)
Interestingly, Iterator does not implement Iterable. So if you have an iterator, you can't use it in a for-each loop.
Right. As a consequence, you rarely if ever want to pass around an Iterator, because you can't easily get an Iterable from it. Well you can do it certainly, but it's not in a standard library:
Which is an annoying bit of boilerplate to have to add on. Sigh. Anyway, the result is that it's usually easier to pass around the Collection that you get the Iterator from, rather than the actual Iterator.