I am trying to understand a java program, which has开发者_如何学运维 a code segment such as
for (final Document document : cluster.getDocuments()) {
if (documentsShown >= maxNumberOfDocumentsToShow) {
break;
}
displayDocument(level + 1, document);
documentsShown++;
}
Does this mean that cluster.getDocuments()
must be an iterator object?
It needs to be an iterable object (i.e. collection or array). Basically,
It's commonly used to iterate over an array or a Collections class (eg, ArrayList). It can also iterate over anything that implements the Iterable interface (must define iterator() method). Many of the Collections classes (eg, ArrayList) implement Iterable, which makes the for-each loop very useful. You can also implement Iterable for your own data structures.
Reference
All Known Implementing Classes of Iterable
The collection over which you iterate must implement the Iterable<E>
interface so that the code is internally compiled into
Iterator<Document> iterator = cluster.getDocuments().iterator();
while (iterator.hasNext()) {
// iteration
}
Of course this means that you can provide custom iteration for custom object if you provide that Iterable
interface.
Not necessarily an iterator object, but it needs to be able to be iterated over (array, list, set, etc...)
No, what is nice about java is that all of its collections implement the Collection interface so the for-each construct works on collections. Cluster.getDocuments()
is most likely some kind of collection.
To use the for-each construct though an object need only implement the Iterable interface, of which Collection is a subclass.
精彩评论