The java.util package contains an Iterator class that makes iterating over a collection a relatively simple task. To iterate over a collection object, you first obtain an Iterator object by calling the iterator() method on the collection object. Once you have the Iterator object, you can step though it using the next() method. The next() method will return the next item in the collection. Because the next() method returns a generic Object type, you should cast the return value to be the type you are expecting. Using the hasNext() method, you can check to see if there are additional elements that have not yet been processed. This makes it convenient to create a "for" loop as shown in this phrase to step through all the elements in a collection. In the previous phrase, we show how to iterate over a set or list, the keys of a map, the values of a map, and both keys and values of a map. Note You might want to use iterators to expose collections through APIs. The advantage of exposing the data through an iterator is that the calling code does not have to know or care about how the data is stored. With this implementation, you could change the collection type without having to change the API. |