View Javadoc

1   package cz.cuni.amis.utils.maps;
2   
3   import java.util.Collection;
4   import java.util.HashMap;
5   import java.util.Map;
6   import java.util.Map.Entry;
7   import java.util.Set;
8   
9   /**
10   * Maps whose items are initialized on demand by create(K) method.
11   * @author ik
12   */
13  public abstract class LazyMap<K, V> implements Map<K, V> {
14  
15      Map<K, V> map = null;
16  
17      /**
18       * Creates value for given key.
19       * @param key
20       * @return
21       */
22      protected abstract V create(K key);
23  
24      public LazyMap() {
25          map = new HashMap<K, V>();
26      }
27  
28      public LazyMap(Map<K, V> baseMap) {
29          map = baseMap;
30      }
31  
32  
33      @Override
34      public int size() {
35          return map.size();
36      }
37  
38      @Override
39      public boolean isEmpty() {
40          return map.isEmpty();
41      }
42  
43      @Override
44      public boolean containsKey(Object key) {
45          return map.containsKey(key);
46      }
47  
48      @Override
49      public boolean containsValue(Object value) {
50          return map.containsValue(value);
51      }
52  
53      @Override
54      public V get(Object key) {
55          V val = map.get((K)key);
56          if(val == null) {
57          	synchronized(this) {
58          		val = map.get((K)key);
59          		if (val != null) return val;
60  	            val = create((K)key);
61  	            if(val != null) {
62  	                map.put((K)key, val);
63  	            }
64          	}
65          }
66          return val;
67      }
68  
69      @Override
70      public V put(K key, V value) {
71      	return map.put(key, value);
72      }
73  
74      @Override
75      public V remove(Object key) {
76          return map.remove(key);
77      }
78  
79      @Override
80      public void putAll(Map<? extends K, ? extends V> m) {
81          map.putAll(m);
82      }
83  
84      @Override
85      public void clear() {
86          map.clear();
87      }
88  
89      @Override
90      public Set<K> keySet() {
91          return map.keySet();
92      }
93  
94      @Override
95      public Collection<V> values() {
96          return map.values();
97      }
98  
99      @Override
100     public Set<Entry<K, V>> entrySet() {
101         return map.entrySet();
102     }
103 
104 }