Maps
already held a value, so all you needed to do was add a key and modify setValue() slightly to return the original value, just as you did with the DefaultEntry earlier.
Next, the original insert() method has been renamed to set(). Whereas the original insert() method worked off values and allowed duplicates, the map uses keys, all of which must be unique. Additionally, set() returns any value previously associated with the key.
The while loop in the original insert() method looked like this:
while (node != null) { parent = node;
cmp = _comparator.compare(value, node.getValue()); node = cmp <= 0 ? node.getSmaller() : node.getLarger();
}
Notice that when a duplicate value was inserted, it would always be added as a left child of any similar value. The set() method now looks like this:
while (node != null) { parent = node;
cmp = _comparator.compare(key, node.getKey()); if (cmp == 0) {
return node.setValue(value);
}
node = cmp < 0 ? node.getSmaller() : node.getLarger();
}
Here, if an existing key is found (cmp == 0), the method updates the value and returns the old value immediately; otherwise, the code proceeds as per the original.
The next change is that the search() method has been made private, and instead there is the contains() method as required by the Map interface. The contains() method then returns true only if search actually finds a matching node.
Apart from the addition of the clear(), isEmpty(), size(), and iterator() methods — again mandated by the Map interface — the only other change of note is the EntryIterator inner class, which iterates forwards or backwards over the nodes in order — and therefore the entries — by calling successor() and predecessor(), respectively.
That’s it: a map implementation that, as you know from Chapter 10, has an average performance of O(log N) as well as the added bonus of maintaining the entries in order, sorted by key.
Summar y
This chapter demonstrated the following:
Maps store values associated with a key.
Each key within a map is unique and enables you to quickly locate its associated value.