Java.util.Map maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map.
All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the SDK comply.
The "destructive" methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be "superimposed" is empty.
Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

 

Creating a Set, Insert, Retrieve and Remove members

A hash map, or table holds key/value pairs.

    // Create a hash table
    Map map = new HashMap();    // hash table
    map = new TreeMap();        // sorted map
   
    // Add key/value pairs to the map
    map.put("a", new Integer(1));
    map.put("b", new Integer(2));
    map.put("c", new Integer(3));
   
    // Get number of entries in map
    int size = map.size();        // 2
   
    // Adding an entry whose key exists in the map causes
    // the new value to replace the old value
    Object oldValue = map.put("a", new Integer(9));  // 1
   
    // Remove an entry from the map and return the value of the removed entry
    oldValue = map.remove("c");  // 3
   
    // Iterate over the keys in the map
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
        // Get key
        Object key = it.next();
    }
   
    // Iterate over the values in the map
    it = map.values().iterator();
    while (it.hasNext()) {
        // Get value
        Object value = it.next();
    }

 

Creating a Map That Retains Order-of-Insertion

    Map map = new LinkedHashMap();
   
    // Add some elements
    map.put("1", "value1");
    map.put("2", "value2");
    map.put("3", "value3");
    map.put("2", "value4");
   
    // List the entries
    for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
        Object key = it.next();
        Object value = map.get(key);
    }
    // [1=value1, 2=value4, 3=value3]

 

Automatically Removing an Unreferenced Element from a Hash Map/Table

When a key is added to a map, the map will prevent the key from being garbage-collected. However, a weak map will automatically remove a key if the key is not being referenced by any other object. An example where this type of map might be useful is a registry where a registrant is automatically removed after it is garbage-collected.

    // Create the weak map
    Map weakMap = new WeakHashMap();
   
    // Add a key to the weak map
    weakMap.put(keyObject, valueObject);
   
    // Get all keys that are still being referenced
    Iterator it = weakMap.keySet().iterator();
    while (it.hasNext()) {
        // Get key
        Object key = it.next();
    }

The weak map does not automatically release the value if it is no longer used. To enable automatically release of the value, the value must be wrapped in a WeakReference object:

    WeakReference weakValue = new WeakReference(valueObject);
    weakMap.put(keyObject, weakValue);
   
    // Get all keys that are still being referenced and check whether
    // or not the value has been garbage-collected
    it = weakMap.keySet().iterator();
    while (it.hasNext()) {
        // Get key
        Object key = it.next();
   
        weakValue = (WeakReference)weakMap.get(key);
        if (weakValue == null) {
            // Value has been garbage-collected
        } else {
            // Get value
            valueObject = weakValue.get();
        }
    }

Creating a Type-Specific Map [5.0]

Generics can be used to create a map that will hold only objects of a certain type. This example creates a map whose keys are Integer objects and values are String objects.

    Map<Integer, String> map = new HashMap<Integer, String>();
   
    map.put(1, "first");
    map.put(2, "second");
    // map.put(1, 2);       <- Syntax error

A map declared to hold objects of a type T can also hold objects that extend from T. In this example, a map is created to hold Number objects as keys. Both Integer and Float are subclasses of Number.

    Map<Number, String> numMap = new HashMap<Number, String>();
   
    numMap.put(.5, "half");
    numMap.put(1, "first");

Note that although null is not a subclass of any type, if the collection supports null values, it can be added to the type-specific collection.

    map.put(null, null);

A value retrieved from a type-specific collection does not need to be casted. In this example, a URL value is retrieved and used without an explicit cast.

    Map<String, URL> urlMap = new HashMap<String, URL>();
    try {
        urlMap.put("java", new URL("http://exampledepot.com/"));
    } catch (MalformedURLException e) {
    }
    String s = urlMap.get("java").getHost();