Java Reference
In-Depth Information
@return an iterator that provides sequential access to the search
keys in the dictionary */
public Iterator<K> getKeyIterator();
/** Creates an iterator that traverses all values in this dictionary.
@return an iterator that provides sequential access to the values
in this dictionary */
public Iterator<V> getValueIterator();
/** Sees whether this dictionary is empty.
@return true if the dictionary is empty */
public boolean isEmpty();
/** Gets the size of this dictionary.
@return the number of entries (key-value pairs) currently
in the dictionary */
public int getSize();
/** Removes all entries from this dictionary. */
public void clear();
} // end DictionaryInterface
19.5
Let's see how to create an instance of a class Dictionary that implements DictionaryInterface .
This dictionary will contain data about the students at your school. Assume that student numbers
are the search keys and that we have the class Student to represent the student data. The following
statement creates the instance dataBase :
DictionaryInterface<String, Student> dataBase =
new Dictionary<String, Student>();
String corresponds to the parameter K in DictionaryInterface , so each occurrence of K in
the interface is replaced by String . Similarly, Student replaces every occurrence of V in the inter-
face. The same correspondence occurs between these actual types and the generic types of the class
Dictionary .
We will examine several examples of dictionaries in more detail later in this chapter.
Iterators
19.6
The methods getKeyIterator and getValueIterator each return an iterator that conforms to the
interface java.util.Iterator that we discussed in Chapter 15. You can create iterators for the
dictionary dataBase that we instantiated in the previous segment by writing
Iterator<String> keyIterator = dataBase.getKeyIterator();
Iterator<Student> valueIterator = dataBase.getValueIterator();
Recall that Iterator specifies a generic type in its definition. Here we have defined an iterator for
the String search keys and another for the Student values.
You can use each of these iterators either separately or together. That is, you can traverse
All of the search keys in a dictionary without traversing the values
All of the values without traversing the search keys
All the search keys and all the values in parallel
 
 
Search WWH ::




Custom Search