Map

From Wikibooks, open books for an open world
Jump to: navigation, search

ArrayList Java Programming
Map
Comparing Objects
Navigate Aggregate topic: v  d  e )


Aside from the java.util.Collection interface, the Java JDK has the java.util.Map interface as well. It is sometimes also called an Associated Array or a Dictionary. A map defines key value mappings. Implementations of the Map interface do not contain collections of objects. Instead they contain collections of key->value mappings. It can be thought of as an array where the index doesn't need to be an integer.

Example Code section 5.17: Use of a map.
  1. import java.util.Map;
    
  2. import java.util.Hashtable;
    
  3. ...
    
  4. Map map = new Hashtable();
    
  5. ...
    
  6. map.put(key, value);
    

Use the Map interface if you need to keep related objects together in a Map where you can:

  • Access an element by a key object
  • Map one object to other


Figure 5.6: Map Interfaces.
Java map interfaces.svg


java.util.Map<K,V> 
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 key is usually a non-mutable object. The value object however can be a mutable object.
java.util.SortedMap<K,V> 
same as the Map interface, plus the keys in the Map are sorted.

In the above example, the same operations are made with two different map implementations:

Computer code Code listing 5.4: MapImplementations.java
  1. import java.util.LinkedHashMap;
    
  2. import java.util.Map;
    
  3. import java.util.TreeMap;
    
  4.  
    
  5. /**
    
  6.  * Compare the map implementations.
    
  7.  *
    
  8.  * @author xxx
    
  9.  */
    
  10. public class MapImplementations {
    
  11.  
    
  12.   /**
    
  13.    * Compare the map implementations.
    
  14.    * @param args The execution parameters.
    
  15.    */
    
  16.   public static void main(String[] args) {
    
  17.     processMap(new LinkedHashMap<String, Integer>());
    
  18.  
    
  19.     processMap(new TreeMap<String, Integer>());
    
  20.   }
    
  21.  
    
  22.   /**
    
  23.    * Use a map:
    
  24.    * 1. Fill the map with key-> value.
    
  25.    * 2. Print all the keys.
    
  26.    *
    
  27.    * @param map The used map.
    
  28.    */
    
  29.   public static void processMap(Map<String, Integer> map) {
    
  30.     System.out.println("Process the map");
    
  31.     map.put("3", new Integer(3));
    
  32.     map.put("2", new Integer(2));
    
  33.     map.put("1", new Integer(1));
    
  34.  
    
  35.     for (String key : map.keySet()) {
    
  36.       System.out.println(key);
    
  37.     }
    
  38.   }
    
  39. }
    
Standard input or output Console for Code listing 5.4
Process the map
3
2
1
Process the map
1
2
3

We see that only the TreeMap has sorted the keys. Beware of the generics. The Map interface is tricky. The methods get() and remove() are not generic. This means that you must be careful of the type of the key:

Example Code section 5.18: Tricky generics.
  1. Map<Integer, String> map = new TreeMap<Integer, String>();
    
  2.  
    
  3. map.put(new Integer(1), "Watch");
    
  4. map.put(new Integer(2), "out");
    
  5. map.put(new Integer(3), "!");
    
  6.  
    
  7. map.remove("2");
    
  8.  
    
  9. for (String value : map.values()) {
    
  10.   System.out.println(value);
    
  11. }
    
Standard input or output Console for Code section 5.18
Watch
out
!

The remove() call has done nothing because "2" is a String, not an Integer so no key and value has been found and removed.

Map Classes[edit]

The Map interface has the following implementations:


Figure 5.7: Map class diagram.
Java map implementation.svg


java.util.TreeMap<E>
guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class, not-synchronized.
java.util.Hashtable<E> 
Synchronized, null can not be used as key
java.util.HashMap<E> 
is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls
java.util.concurrent.ConcurrentHashMap 
same as Hashtable, plus retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).
java.util.WeakHashMap<E> 
entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Non-synchronized.
java.util.LinkedHashMap<E> 
This linked list defines the iteration ordering, which is normally the order in which keys were first inserted into the map (first insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.
java.util.IdentityHashMap 
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).) Not-synchronized.
java.util.EnumMap 
All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient. Not-synchronized.

Thread safe maps[edit]

The following table lists all the synchronized map classes:

synchronized non-synchronized
java.util.TreeMap
java.util.Hashtable

java.util.concurrent.ConcurrentHashMap

java.util.HashMap
java.util.LinkedHashMap
java.util.IdentityHashMap
java.util.EnumMap


Clipboard

To do:
Add some exercises like the ones in Variables

ArrayList Java Programming
Map
Comparing Objects