SHARE
TWEET

Untitled

a guest Jul 17th, 2017 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.HashMap;
  2.  
  3. /**
  4.  * This class is an extension of a normal Map which uses two keys to map a
  5.  * single value.
  6.  *
  7.  * @author T-106.1240
  8.  *
  9.  * @param <KeyTypeA>
  10.  *            first key type.
  11.  * @param <KeyTypeB>
  12.  *            second key type.
  13.  * @param <ValueType>
  14.  *            The type of the values contained in the structure.
  15.  */
  16. public class MultiKeyMap<KeyTypeA, KeyTypeB, ValueType> {
  17.  
  18.     // The structure of the MultiKeyMap is internally a HashMap containing
  19.     // HashMaps.
  20.     // This is the "outer" HashMap that contains the "inner" hashmaps.
  21.     //
  22.     // Notice that the key type for this is the type of the first key
  23.     // and the value type of this map is a hashmap that maps the second key
  24.     // to the actual value
  25.  
  26.     private HashMap<KeyTypeA, HashMap<KeyTypeB, ValueType>> outerMap;
  27.  
  28.     /**
  29.      * Constructs an initially empty MultiKeyMap.
  30.      */
  31.     public MultiKeyMap() {
  32.  
  33.         this.outerMap = new HashMap<KeyTypeA, HashMap<KeyTypeB, ValueType>>();
  34.  
  35.     }
  36.  
  37.     /**
  38.      * Inserts the given key,key-value into the Map.
  39.      *
  40.      * @param key1
  41.      *            The first key.
  42.      * @param key2
  43.      *            The second key.
  44.      * @param value
  45.      *            The value corresponding to the keys.
  46.      * @return a previous value corresponding to the key1,key2 pair if there was
  47.      *         one - otherwise null.
  48.      */
  49.     public ValueType put(KeyTypeA key1, KeyTypeB key2, ValueType value) {
  50.         if (this.get(key1, key2) == null) {
  51.             HashMap<KeyTypeB, ValueType> innerMap = new HashMap<KeyTypeB, ValueType>();
  52.             innerMap.put(key2, value);
  53.             this.outerMap.put(key1, innerMap);
  54.             return null;
  55.         } else {
  56.             return this.get(key1, key2);
  57.         }
  58.  
  59.     }
  60.  
  61.     /**
  62.      * Retrieves a value corresponding to the given key,key-pair from the map.
  63.      *
  64.      * @param key1
  65.      *            the first key.
  66.      * @param key2
  67.      *            the second key.
  68.      * @return The value corresponding to the key,key pair.
  69.      */
  70.  
  71.     public ValueType get(KeyTypeA key1, KeyTypeB key2) {
  72.         if (this.outerMap.containsKey(key1)) {
  73.             return this.outerMap.get(key1).get(key2);
  74.         } else {
  75.             return null;
  76.         }
  77.     }
  78.  
  79. }
RAW Paste Data
Top