Java Reference
In-Depth Information
Exercise 4.21 Create a MusicOrganizer and store a few file names in it. Use the
listAllFiles method to print them out; check that the method works as it should.
Exercise 4.22 Create an ArrayList<String> in the Code Pad by typing the following
two lines:
import java.util.ArrayList;
new ArrayList<String>()
If you write the last line without a trailing semicolon, you will see the small red object icon.
Drag this icon onto the object bench. Examine its methods and try calling some (such as add ,
remove , size , isEmpty ). Also try calling the same methods from the Code Pad. You can
access objects on the object bench from the Code Pad by using their names. For example,
if you have an ArrayList named al1 on the object bench, in the Code Pad you can type:
al1.size()
Exercise 4.23 If you wish, you could use the debugger to help you understand how the
statements in the body of the loop in listAllFiles are repeated. Set a breakpoint just be-
fore the loop, and step through the method until the loop has processed all elements and exits.
Exercise 4.24 Challenge exercise The for-each loop does not use an explicit integer vari-
able to access successive elements of the list. Thus, if we want to include the index of each file
name in the listing, then we would have to declare our own local integer variable ( position,
say) so that we can write in the body of the loop something like:
System.out.println(position + ": " + filename);
See if you can complete a version of listAllFiles to do this. Hint: You will need a local
variable declaration of position in the method, as well as a statement to update its value by
one inside the for-each loop.
One of the things this exercise illustrates is that the for-each loop is not really intended to be
used with a separate index variable.
We have now seen how we can use a for-each loop to perform some operation (the loop body)
on every element of a collection. This is a big step forward, but it does not solve all our prob-
lems. Sometimes we need a little more control, and Java provides a different loop construct to
let us do more: the while loop .
4.9.2
Selective processing of a collection
The listAllFiles method illustrates the fundamental usefulness of a for-each loop: it pro-
vides access to every element of a collection, in order, via the variable declared in the loop's
header. It does not provide us with the index position of an element, but we don't always need
that, so that is not necessarily a problem.
Having access to every item in the collection, however, does not mean we have to do the same
thing to every one; we can be more selective than that. For instance, we might want to only list
 
Search WWH ::




Custom Search