Java Reference
In-Depth Information
Note The order of the lines in the output may be different when you run the
StockPortfolio class in your environment because the underlying implementation
uses a HashMap . A HashMap does not guarantee the order of the elements stored in
the map, and this extends to its iterators. If you wanted the iterator to return elements
sorted by the stock symbol, you could use one of the sorted collections, such as
TreeMap or TreeSet , instead of HashMap . Another option is to utilize a stream on
the collection, which is a feature that was introduced in Java 8. See Recipe 7-8 for more
about streams.
How It Works
The Iterable interface was introduced in Java 5 to support the enhanced for loop
(also known as the foreach loop) which was introduced at the same time. Along
with these enhancements to the language, all Collection classes were retrofitted to
implement the Iterable interface, thus allowing Collection classes to be iter-
able using the foreach loop. The Iterable interface is a generic type defined as
follows:
public interface Iterable<T> {
Iterator<T> iterator();
}
Any class that implements Iterable<T> must implement the iterator()
method to return an Iterator<T> object. Typically, the Iterator returned is the
default iterator of the underlying collection; however, it may also return an instance of
a custom Iterator . In the StockPortfolio class, a Map is used to represent the-
stock portfolio. The key for each map entry is the stock symbol, and the value associ-
ated with each key is a Stock object. Maps in Java are not iterable; that is, they are
not Collection classes. Therefore, they do not implement Iterable . However,
both the keys and the values of a map are Collections , and therefore are Iter-
ables . We want our implementation of the Iterable iterator() method to re-
turn an Iterator over the values ( Stock references) of the portfolio map; there-
fore, our Iterable implementation is parameterized by the Stock type:
public class StockPortfolio implements Iterable<Stock>
Search WWH ::




Custom Search