Java Reference
In-Depth Information
result = null
Search the array for an entry containing key
if ( an entry containing key is found in the array )
{
result = value currently associated with key
Replace key 's associated value with value
}
else // insert new entry
{
if ( array is full )
Double size of array
Insert a new entry containing key and value after the last entry in the array
Increment the size of the dictionary
}
return result
FIGURE 20-2
Adding a new entry to an unsorted array-based dictionary
Add a new entry
after all the others
20.5
The method add . The following implementation of the method add invokes the private methods
specified in Segment 20.3:
public V add(K key, V value)
{
V result = null ;
int keyIndex = locateIndex(key);
if (keyIndex < numberOfEntries)
{
// key found; return and replace old value
result = dictionary[keyIndex].getValue();
dictionary[keyIndex].setValue(value);
}
else
{
ensureCapacity();
dictionary[numberOfEntries] = new Entry<K, V>(key, value);
numberOfEntries++;
} // end if
return result;
} // end add
To search an unsorted array, locateIndex has the following definition:
private int locateIndex(K key)
{
int index = 0;
while ( (index < numberOfEntries) &&
!key.equals(dictionary[index].getKey()) )
index++;
return index;
} // end locateIndex
 
Search WWH ::




Custom Search