Java Reference
In-Depth Information
The for loop and iterators
In Section 4.12.2, we showed the necessity of using an Iterator if we wished to remove ele-
ments from a collection. There is a special use of the for loop with an Iterator when we want
to do something like this. Suppose that we wished to remove every music track by a particular
artist from our music organizer. The point here is that we need to examine every track in the
collection, so a for-each loop would seem appropriate, but we know already that we cannot use
it in this particular case. However, we can use a for loop as follows:
for(Iterator<Track> it = tracks.iterator(); it.hasNext(); ) {
Track t =;
if(t.getArtist().equals(artist)) {
The important point here is that there is no post-body action in the loop's header—it is just blank.
This is allowed, but we must still include the semicolon after the loop's condition. By using a for
loop instead of a while loop, it is a little clearer that we intend to examine every item in the list.
Which loop should I use? We have discussed three different loops: the for-each loop, the
while loop, and the for loop. As you have seen, in many situations you have a choice of using either
one of these to solve your task. Usually, one loop could be rewritten using another. So how do you
decide which one to use at any given point? Here are some guidelines:
If you need to iterate over all elements in a collection, the for-each loop is almost always the
most elegant loop to use. It is clear and concise (but it does not give you a loop counter).
If you have a loop that is not related to collections (but instead performs some other action
repeatedly), the for-each loop is not useful. Your choice will be between the for loop and the
while loop. The for-each loop is only for collections.
The for loop is good if you know at the start of the loop how many iterations you need (that is,
how often you need to loop around). This information can be in a variable but should not change
during the loop execution. It is also very good if you need to use the loop counter explicitly.
The while loop should be preferred if, at the start of the loop, you don't know how often you
need to loop. The end of the loop can be determined on the fly by some condition (for example,
repeatedly read one line from a file until we reach the end of the file).
If you need to remove elements from the collection while looping, use a for loop with an
Iterator if you want to examine the whole collection, or a while loop if you might finish before
reaching the end of the collection.
Exercise 4.69 Check to see what happens if the for loop's condition is incorrectly written
using the <= operator in printHourlyCounts :
for(int hour = 0; hour <= hourCounts.length; hour++)
Exercise 4.70 Rewrite the body of printHourlyCounts so that the for loop is replaced
by an equivalent while loop. Call the rewritten method to check that it prints the same results
as before.
Search WWH ::

Custom Search