Java Reference
In-Depth Information
A Problem Solved: A Directory of Telephone Numbers
A telephone directory contains the names and telephone numbers of the people who live in a
given geographical region. Implement software that defines such a directory.
19.7
The most frequent operation performed on a telephone directory is the retrieval of a telephone num-
ber, given a person's name. Thus, using the ADT dictionary to represent a telephone directory is a
good choice. Clearly, the name should be the search key, and the telephone number should be the
corresponding value. Often, but not always, retrieval is more efficient when the dictionary is sorted.
Additionally, a sorted dictionary would make it easier to create a printed directory with entries
alphabetized by name. To simplify this example, we assume that the directory will contain distinct
names with no duplicates.
A major task, at least initially, is to create the directory from the available names and telephone
numbers. Having this data in a text file will make this task convenient. After the telephone direc-
tory is created, operations on the directory, such as adding an entry, removing an entry, or changing
a telephone number, will be used less often than searching for a given name. Traversing the direc-
tory is important to create either a hard copy or a text file of the data, but this operation too is not
done frequently. As we noted in Chapter 4, you should choose an implementation of an ADT based
on the efficiency of its expected use.
19.8
Design and use of the class TelephoneDirectory . Our next step is to design a class to represent the
telephone directory. A sorted dictionary will represent the data, which consists of name-number pairs.
Each person's name can be an instance of the class Name that we first encountered in Appendix B, and
the telephone number can be a string without embedded blanks. Figure 19-4 shows a class diagram for
our design. The class TelephoneDirectory contains an instance phoneBook of a dictionary. The class
has the method readFile , which reads the data from the file and adds it to phoneBook . It also has the
method getPhoneNumber to retrieve a telephone number, given a name. For simplicity, we are ignor-
ing any other operations mentioned in the previous segment.
FIGURE 19-4
A class diagram for a telephone directory
TelephoneDirectory
Dictionary
Name
1
1
*
*
phoneBook
*
readFile(data)
getPhoneNumber(name)
String
*
Before we implement the class TelephoneDirectory , let's consider its use. A client would cre-
ate an instance of TelephoneDirectory and read the data file by invoking the method readFile .
 
 
 
Search WWH ::




Custom Search