Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
How It Works
The ArrayList framework. The ArrayList implements the Collection of common operations for all collection types, and the List of operations that are specific to the list-oriented Collection framework makes heavy use of Java generics. The StockScreener main() method starts by declaring a List specifying with the generic type parameter, that the stocks list elements are of type String. Notice that the actual list type is an ArrayList The stocks list holds a variable number of stocks, represented by their stock market symbol (a string). List 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 several calls to the ArrayList 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 with 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 run the screen for each stock, and remove those stocks that do not pass the screen. Note that to safely remove an element from a Collection use iterate using the Collection its iterator() method. Here, we show the use of a while loop to iterate 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. Chapter 7 Data SourCeS anD ColleCtionS 272 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 produce unexpected results. at some point, the code also throws ConcurrentModificationException, regardless of whether you have multiple threads accessing the same list. remember to always remove elements through the iterator when iterating over any Collection The ArrayList place of the array type. It provides more flexibility than a simple array because elements can be added and removed dynamically with ease. While it is true that ArrayList an array internally, you benefit from optimized add() and remove() operations that are implemented for you. Also, ArrayList Refer to Java documentation for more information ( https://docs.oracle.com/en/ java/javase/17/docs/api/java.base/java/util/ArrayList.html ). Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling