Java Reference
In-Depth Information
private V getValue()
{
return value;
} // end getValue
private void setValue(V newValue)
{
value = newValue;
} // end setValue
} // end Entry
} // end SortedVectorDictionary
20.18
The method add . The implementation of the method add is similar to the one given earlier in
Segment 20.11 for the sorted array-based implementation. This version is shorter, since much of
the busy work is handled for us by Vector . You should compare this code with the code given
earlier.
Assuming that we have already revised locateIndex , as given in Segment 20.12, to work with
vectors, we call it with the statement
int keyIndex = locateIndex(key);
where key is the search key of the new entry. To see whether an entry having key as its search key
is already in the dictionary, we check whether key is the same as the search key of the entry at
keyIndex . Using Vector 's method get , we reference this entry by writing
dictionary.get(keyIndex)
To get this entry's search key, we write
( dictionary.get(keyIndex) ) .getKey()
The pair of blue parentheses is optional. This expression is now the argument of the method equals
that is invoked by key , the new entry's search key:
key.equals((dictionary.get(keyIndex)).getKey())
Ordinarily, we could simplify this expression by first assigning the argument of equals to a local
variable, as follows:
Entry currentEntry = dictionary.get(keyIndex);
We then could write the expression as
key.equals(currentEntry.getKey())
But in our case, we also need to check the value of keyIndex . Thus, we are left with the choice of
one long if clause or several awkwardly nested but shorter if statements. We settle for the follow-
ing implementation of add :
public V add(K key, V value)
{
V result = null ;
int keyIndex = locateIndex(key);
if ( (keyIndex < dictionary.size()) &&
key.equals( (dictionary.get(keyIndex)).getKey() ) )
{
// key found; return and replace old value
Search WWH ::




Custom Search