Java Reference
In-Depth Information
In the last case, the i th search key returned by keyIterator corresponds to the i th dictionary value
returned by valueIterator , as Figure 19-3 illustrates. Clearly, the two iterations have the same
length, since the number of search keys in a dictionary must be the same as the number of values.
FIGURE 19-3
Two iterators that traverse a dictionary's keys and values in parallel
Search keys
Corresponding values
keyIterator.next()
valueIterator.next()
A dictionary object
The following loop displays each entry in the dictionary as a key-value pair:
while (keyIterator.hasNext())
System.out.println(keyIterator.next() + ", " + valueIterator.next());
For a sorted dictionary, keyIterator traverses the search keys in sorted order. For an unsorted
dictionary, this traversal order is not specified. The examples in the next section demonstrate these
iterators in several contexts.
Note: An iteration of a dictionary's values corresponds to an iteration of its search keys.
That is, the i th value in one iteration is associated in the dictionary with the i th search key in
the second iteration.
Question 1 If the class Dictionary implements DictionaryInterface , write a Java state-
ment that creates an empty dictionary myDictionary . This dictionary will contain the names
and telephone numbers of your friends. Assume that the names are the search keys, and you
have the class Name to represent them. Let each telephone number be a string.
Question 2 Write a Java statement that adds your name and telephone number to the dic-
tionary that you created in Question 1.
Question 3 Write Java statements that display either Britney Storm's telephone number, if
she is in the dictionary described in Question 1, or an error message if she is not.
Using the ADT Dictionary
The three examples in this section demonstrate how to use the ADT dictionary in a program. We
begin by creating a telephone directory.
VideoNote
Using the ADT dictionary
 
 
Search WWH ::




Custom Search