![]() ![]() Of course the operation being performed on the elements in a collection could possibly change some of the elements. An iterator should also be nondestructive in the sense that the act of iteration should not, by itself, change the collection. (You could also use the Visitor pattern in this context.)Ĭertain principles hold for the use of iterators: In general, you should be able to have multiple traversals in progress at the same time that is, an iterator should allow for the concept of nested looping. Visit each node in a compiler's abstract syntax tree (which is produced by the parser) and perform semantic checking or code generation.Visit each customer in a queue (for instance, simulating a line in a bank) and find out how long he or she has been waiting.Visit each node in a graph and determine whether it is reachable from a given node.Visit each file in a directory ( aka folder) and display its name.Essentually, an iterator provides a means of "looping" over an encapsulated collection of objects. The Iterator patternĪn iterator is a mechanism that permits all elements of a collection to be accessed sequentially, with some operation being performed on each element. Java includes various mechanisms for iteration, including index (for iterating over an array), cursor (for iterating over the results of a database query), enumeration (in early versions of Java), and iterator (in more recent versions of Java). Similarly, in the programming world, we need a mechanism to systematically iterate through a collection of software objects. ![]() As an everyday example, consider the television remote control, which lets us iterate through various television channels. Anytime you have a collection of things you will need some mechanism to systematically step though the items in that collection. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |