Map ADT Specification

Here is the fully specified Map ADT:

/**
 * A Map is a collection of key-value pairs with distinct keys and no order.
 * @param <K> the type of keys in this map
 * @param <V> the type of values in this map
 */
public interface Map<K, V> {
  /**
   * Associates the given value with the given key. If the key is already
   * present, its value is replaced with the given value.
   * @param key the key to add or update
   * @param value the value to associate with the key
   * @return true if the key was not previously present, false if it was
   * @throws IllegalArgumentException if the key or the value is null
   */
  boolean put(K key, V value);

  /**
   * Returns the value associated with the given key, or null if the key
   * is not present.
   * @param key the key to look up
   * @return the value associated with the key, or null if the key is absent
   * @throws IllegalArgumentException if the key is null
   */
  V get(K key);

  /**
   * Removes the given key and its value from this map if the key is present.
   * @param key the key to remove
   * @return true if the key was removed, false if it was not present
   * @throws IllegalArgumentException if the key is null
   */
  boolean remove(K key);

  /**
   * Returns true if this map contains the given key.
   * @param key the key to look for
   * @return true if the key is present, false otherwise
   * @throws IllegalArgumentException if the key is null
   */
  boolean containsKey(K key);

  /**
   * Returns the number of key-value pairs in this map.
   * @return the number of pairs in this map
   */
  int size();
}

As in the set, put and remove return whether the call changed the map. But pay attention to the put specification. It returns true if the key was not previously present, and false if it was already there. In the latter case, the value is replaced, but the key is still there. So a more accurate statement is that put and remove return whether the call changed the keys in the map.

get returns the value associated with a key, or null if the key is not present. For the latter to hold, we must reject null values. Otherwise, a null return value could mean either that the key is absent or that the key is present but associated with a null value.

You can find a suite of tests for this interface in the MapTest class within the code accompanying this chapter.