Java Reference
In-Depth Information
22. f.addFavorite(“sybex.com”);
23. f.addFavorite(“wiley.com”);
24. f.addFavorite(“http://google.com”);
25. f.addFavorite(“yahoo.com”);
26. f.showFavorites();
27. }
28.}
The sequence of events of the Favorites program follows:
1. A Favorites object is instantiated in main and four String objects are added to the
urls field.
2. The showFavorites method is invoked, which executes the enhanced for loop on line 7.
3. The first time through the loop the iterator url is “sybex.com” and “http://sybex.com”
displays.
4. The loop iterates three more times until all four String objects are output.
The output of main in Favorites is
http://sybex.com
http://wiley.com
http://google.com
http://yahoo.com
When to Use—or Not Use—Enhanced for Loops
The enhanced for statement was added to the Java language to simplify your code in
those common situations where you need to iterate over an array or collection of objects.
You will use enhanced for loops all the time when iterating over arrays and collections.
Notice that the enhanced for loop hides the index variable when iterating over arrays,
and it hides the actual iterator when iterating over collections. For example, suppose you
need to iterate over an array and change each element. You won't be able to do that with
an enhanced for loop because you won't have the index variable of the array. Similarly,
suppose you want to delete the element in a collection represented by the current
iterator. You may not be able to do this (depending on the collection) because the iterator
does not know of its location in the collection. In these situations, you can simply use a
basic for loop for iterating over the array or collection.
Search WWH ::




Custom Search