Java Reference
In-Depth Information
System.out.println(files.get(0));
System.out.println(files.get(1));
System.out.println(files.get(2));
etc. How many println statements would be required to complete the method?
You have probably appreciated that it is not really possible to complete Exercise 4.19, because
it depends on how many file names are in the list at the time they are printed. If there are three,
then three println statements would be required; if there are four, then four statements would
be needed; and so on. The listFile and removeFile methods illustrate that the range of
valid index numbers at any one time is [0 to (size()-1)] . So a listAllFiles method
would also have to take that dynamic size into account in order to do its job.
What we have here is the requirement to do something several times, but the number of times
depends upon circumstances that may vary—in this case, the size of the collection. We shall
meet this sort of requirement in nearly every program we write, and most programming lan-
guages have several ways to deal with it through the use of loop statements , which are also
known as iterative control structures .
The first loop we will introduce to list the files is a special one for use with collections, one that
completely avoids the need to use an index variable at all: it is called a for-each loop.
4.9.1
The for-each loop
A for-each loop is one way to perform a set of actions repeatedly on the items in a collection,
but without having to write out those actions more than once, as we saw was a problem in
Exercise 4.19. We can summarize the Java syntax and actions of a for-each loop in the follow-
ing pseudo-code:
Concept:
A loop can be
used to execute
a block of state-
ments repeatedly
without having to
write them multiple
times.
for( ElementType element : collection ) {
loop body
}
The main new piece of Java is the word for . The Java language has two variations of the for
loop: one is the for-each loop , which we are discussing here; the other one is simply called a for
loop and will be discussed later in this chapter.
A for-each loop has two parts: a loop header (the first line of the loop statement) and a loop
body following the header. The body contains those statements that we wish to perform over
and over again.
The for-each loop gets its name from the way we can read this loop: if we read the keyword
for as “for each” and the colon in the loop header as “in,” then the code structure shown above
slowly starts to make more sense, as in this non-Java pseudo-code:
for each element in collection do : {
loop body
}
 
Search WWH ::




Custom Search