Java Reference
In-Depth Information
Code 4.1
continued
The MusicOrganizer
class
public void listFile( int index)
{
if (index >= 0 && index < files.size()) {
String filename = files.get(index);
System.out.println(filename);
}
}
/**
* Remove a file from the collection.
* @param index The index of the file to be removed.
*/
public void removeFile( int index)
{
if (index >= 0 && index < files.size()) {
files.remove(index);
}
}
}
4.4.1
Importing a library class
The very first line of the class file illustrates the way in which we gain access to a library class
in Java, via an import statement:
import java.util.ArrayList;
This makes the ArrayList class from the java.util package available to our class definition.
Import statements must always be placed before class definitions in a file. Once a class name has
been imported from a package in this way, we can use that class just as if it were one of our own
classes. So we use ArrayList at the head of the MusicOrganizer class to define a files field:
private ArrayList<String> files;
Here, we see a new construct: the mention of String in angle brackets: <String> . The need
for this was alluded to in Section 4.3, where we noted that ArrayList is a general-purpose
collection class—i.e., not restricted in what it can store. When we create an ArrayList object,
however, we have to be specific about the type of objects that will be stored in that particular
instance. We can store whatever type we choose, but we have to designate that type when de-
claring an ArrayList variable. Classes such as ArrayList , which get parameterized with a
second type, are called generic classes (we will discuss them in more detail later).
When using collections, therefore, we always have to specify two types: the type of the collec-
tion itself (here: ArrayList ) and the type of the elements that we plan to store in the collection
(here: String ). We can read the complete type definition ArrayList<String> as “ ArrayList
of String .” We use this type definition as the type for our files variable.
As you should now have come to expect, we see a close connection between the body of
the constructor and the fields of the class, because the constructor is responsible for initializing
the fields of each instance. So, just as the ClockDisplay created NumberDisplay objects for
 
Search WWH ::




Custom Search