Java Reference
In-Depth Information
The ArrayList is a very useful data structure that should normally be used in
place of the array type. It provides much more flexibility than a simple array, in that
elements can be added and removed dynamically with ease. While it is true that Ar-
rayList uses an array internally, you benefit from optimized add() and re-
move() operations that are implemented for you. Also, ArrayList implements
many other very useful methods. Refer to the online Java documentation for further de-
tails ( http://download.java.net/jdk8/docs/api/java/util/Ar-
rayList.html ).
7-7. Making Your Objects Iterable
Problem
You have created a custom collection-based class that wraps (instead of extends) the
underlying collection type. Without exposing the internal implementation details of
your class, you would like objects of your class to be iterable, especially with the use
of a foreach statement.
Solution
Have your class extend the Interable<T> interface, where T is the element type of
the collection to be iterated. Implement the iterator() method to return the Iter-
ator<T> object from this collection. The example for this recipe is the Stock-
Portfolio class. Internally, StockPortfolio manages a collection of Stock
objects. We would like users of our class to be able to treat StockPortfolio ob-
jects as iterable objects using a foreach statement. The StockPortfolio class
follows:
// See StockPortfolio.java and Stock.java
public class StockPortfolio implements Iterable<Stock> {
Map<String, Stock> portfolio = new HashMap<>();
public void add(Stock stock) {
portfolio.put(stock.getSymbol(), stock);
}
Search WWH ::




Custom Search