Java Reference
In-Depth Information
We shall find that the ArrayList class makes it very easy to provide this functionality from
our own class.
Notice that we are not being too ambitious in this first version. These features will be sufficient
for illustrating the basics of creating and using the ArrayList class, and later versions will
then build further features incrementally until we have something more sophisticated. (Most
importantly, perhaps, we will later add the possibility of playing the music files. Our first ver-
sion will not be able to do that yet.) This modest, incremental approach is much more likely to
lead to success than trying to implement everything all at once.
Before we analyze the source code needed to make use of such a class, it is helpful to explore
the starting behavior of the music organizer.
Exercise 4.1 Open the music-organizer-v1 project in BlueJ and create a MusicOrganizer
object. Store the names of a few audio files into it—they are simply strings. As we are not go-
ing to play the files at this stage, any file names will do, although there is a sample of audio files
in the audio sub-folder of the project that you might like to use.
Check that the number of files returned by numberOfFiles matches the number you stored.
When you use the listFile method, you will need to use a parameter value of 0 (zero) to
print the first file, 1 (one) to print the second, and so on. We shall explain the reason for this
numbering in due course.
Exercise 4.2 What happens if you create a new MusicOrganizer object and then call
removeFile(0) before you have added any files to it? Do you get an error? Would you ex-
pect to get an error?
Exercise 4.3 Create a MusicOrganizer and add two file names to it. Call listFile(0)
and listFile(1) to show the two files. Now call removeFile(0) and then list-
File(0) . What happened? Is that what you expected? Can you find an explanation of what
might have happened when you removed the first file name from the collection?
Using a library class
Code 4.1 shows the full definition of our MusicOrganizer class, which makes use of the li-
brary class ArrayList . Note that library classes do not appear in the BlueJ class diagram.
Class libraries One of the features of object-oriented languages that makes them powerful is
that they are often accompanied by class libraries. These libraries typically contain many hundreds
or thousands of different classes that have proved useful to developers on a wide range of differ-
ent projects. Java calls its libraries packages. Library classes are used in exactly the same way as
we would use our own classes. Instances are constructed using new , and the classes have fields,
constructors, and methods.
Search WWH ::

Custom Search