Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet143/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   139   140   141   142   143   144   145   146   ...   245
Bog'liq
Java 17 Recipes

 How It Works
The Iterable interface was introduced in Java 5 to support the enhanced for 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 iterable using the foreach loop. The Iterable 
interface is a generic type defined as follows.
public interface Iterable {
Iterator iterator();
}
Any class that implements Iterable must implement the iterator() method 
to return an Iterator 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 represents the stock portfolio. 
The key for each map entry is the stock symbol, and the value associated with each 
key is a Stock object. Maps in Java are not iterable; 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 Iterables. We want our implementation 
of the Iterable iterator() method to return an Iterator over the values 
(stock references) of the portfolio map; therefore, our Iterable implementation is 
parameterized by the stock type.
public class StockPortfolio implements Iterable
Chapter 7 Data SourCeS anD ColleCtionS


276
The Map values() method returns the Collection of map values; in this 
case, a Collection of Stocks. The iterator() method implementation can then 
simply return the Iterator for this Collection.
@Override
public Iterator iterator() {
return portfolio.values().iterator();
}
With this implementation of Iterable, either the legacy a foreach loop, or the 
forEach implementation can iterate a StockPortfolio instance and print each stock.
myPortfolio.forEach(s->System.out.println(s));
The forEach method was new to the Iterable interface with the release of Java 8.
The method performs the specified action for each element within the Iterable until 
all elements have been processed, or the specified action throws an exception. In this 
solution, the specified action is a lambda expression (see Chapter 
6
), which prints the 
value of each element within the myPortfolio iterable.
You notice that StockPortfolio also contains the add(List) method, which 
allows the portfolio to be populated from a List. This method also uses a foreach 
loop to iterate the input List . Again, this is possible because Lists are Iterables. 
(Note that this method is never called in the code; it exists only for illustration purposes.)
Note there’s one issue with our implementation of Stockportfolio. We have 
gone to great lengths not to expose the internal implementation details of our 
class (the portfolio map). this allows us to change the implementation without 
affecting the Stockportfolio client code. however, when we implemented 
Iterable , we effectively exported the underlying portfolio map 
through the iterator() method. unfortunately, Java does not provide an 
UnmodifiableIterator class that could wrap an iterator and prevent 
modification of the underlying collection. however, it would be simple to implement 
such a class that forward the hasNext() and next() calls to the wrapped 
iterator but leaves the remove() method unimplemented (per the iterator Java 
documentation, UnsupportedOperationException should be thrown). 
alternatively, your iterator() method could return the iterator from an 
Chapter 7 Data SourCeS anD ColleCtionS


277
unmodifiable Collection obtained through a call to the Collections.
unmodifiableCollection() class method. You are encouraged to 
explore these two options. to give you a start, one possible implementation of 
UnmodifiableIterator has been provided in the source code download (see 
UnmodifiableIterator.java).
As you have seen in this recipe, the Iterable interface allows you to create 
iterable objects compatible with a foreach implementation. This is very useful when 
designing a custom collection-based class that encapsulates implementation details. 
Keep in mind that to enforce the encapsulation and prevent modification of your 
underlying collection, you should implement one of the solutions mentioned in the 
preceding note.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   139   140   141   142   143   144   145   146   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling