Java Reference
In-Depth Information
When you compare this version to the original pseudo-code in the first version, you notice that
element was written in the form of a variable declaration as ElementType element . This sec-
tion does indeed declare a variable that is then used for each collection element in turn. Before
discussing further, let us look at an example of real Java code.
Code 4.3 shows an implementation of a listAllFiles method that lists all file names cur-
rently in the organizer's ArrayList that use such a for-each loop.
Code 4.3
Using a for-each loop
to list the file names
* Show a list of all the files in the collection.
public void listAllFiles()
for (String filename : files) {
In this for-each loop, the loop body—consisting of a single System.out.println statement —is
executed repeatedly, once for each element in the files ArrayList . If, for example, there were
four strings in the list, the println statement would be executed four times.
Each time before the statement is executed, the variable filename is set to hold one of the list
elements: first the one at index 0 , then the one at index 1 , and so on. Thus, each element in the
list gets printed out.
Let us dissect the loop in a little more detail. The keyword for introduces the loop. It is fol-
lowed by a pair of parentheses, within which the loop details are defined. The first of the details
is the declaration String filename ; this declares a new local variable filename that will be
used to hold the list elements in order. We call this variable the loop variable. We can choose
the name of this variable just as we can that of any other variable; it does not have to be called
“filename.” The type of the loop variable must be the same as the declared element type of the
collection we are going to use— String in our case.
Then follows a colon and the variable holding the collection that we wish to process. From this
collection, each element will be assigned to the loop variable in turn; and for each of those as-
signments, the loop body is executed once. In the loop body, we then use the loop variable to
refer to each element.
To test your understanding of how this loop operates, try the following exercises.
Exercise 4.20 Implement the listAllFiles method in your version of the music-
organizer project. (A solution with this method implemented is provided in the music-
organizer-v3 version of this project, but to improve your understanding of the subject, we
recommend that you write this method yourself.)
Search WWH ::

Custom Search