Java Reference
In-Depth Information
mended that you read Recipe 7-5, which gives a brief summary of generics and their
use with collections.
The StockScreener main() method starts by declaring a List of stocks,
and specifying with the generic type parameter, that the stocks list elements will be of
type String . Notice that the actual list type is an ArrayList that is created using
the diamond, which is discussed in Recipe 7-5. The stocks list will hold a variable
number of stocks, represented by their stock market symbol (a String ):
List<String> stocks = new ArrayList<>();
Now that you've specified that the stocks list can only hold strings, all the List
methods, in turn, get parameterized to only allow strings. So, next, the code makes sev-
eral calls to the ArrayList 's add(String) method to add the stocks to the list.
After that, a screen is run on GOOG (Google) based on its Beta (a measure of stock
risk); if it does not pass the screen, the List remove(String) method is called to
remove the stock from the stock list. Two more screens are then run on the entire stock
list to get a list of stocks that have a P/E of 22.0 or less, and a Yield of 3.5% or more.
The screen() method used for these screens takes a parameter of type
List<String> . It has to iterate over the list, run the screen for each stock in the list,
and remove those stocks that do not pass the screen. Note that in order to safely remove
an element from a Collection while iterating over it, you must use iterate using the
Collection 's Iterator , which can be obtained by calling its iterator()
method. Here, we are showing the use of a while loop to iterate over the stocks list (a
for loop could similarly be used). As long as you're not to the end of the list
( iter.hasNext() ), you can get the next stock from the list ( iter.next() ), run
the screen, and remove the element from the list ( iter.remove() ) if the screen
didn't pass.
Note You may find that calling the list's remove() method while iterating the list
seems to work. The problem is that it's not guaranteed to work and will produce unex-
pected results. At some point, the code will also throw a ConcurrentModifica-
tionException , regardless of whether you have multiple threads accessing the same
list. Remember to always remove elements through the iterator when iterating over any
Collection .
Search WWH ::




Custom Search