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.Set;
7   
8   public class CountIntMap<KEY> implements Map<KEY, Integer>{
9   	
10  	private HashMap<KEY, Integer> counts = new HashMap<KEY, Integer>();
11  	
12  	@Override
13  	public void clear() {
14  		counts.clear();
15  	}
16  	
17  	@Override
18  	public Set<KEY> keySet() { 
19  		return counts.keySet();
20  	}
21  
22  	@Override
23  	public Set<Entry<KEY, Integer>> entrySet() {
24  		return counts.entrySet();
25  	}
26  	
27  	@Override
28  	public Collection<Integer> values() {
29  		return counts.values();
30  	}
31  	
32  	@Override
33  	public Integer get(Object key) {
34  		Integer value = counts.get(key);
35  		if (value == null) {
36  			counts.put((KEY) key, 0);
37  			return 0;
38  		}
39  		return value;
40  	}
41  	
42  	@Override
43  	public Integer remove(Object key) {
44  		return counts.remove(key);
45  	}
46  	
47  	/**
48  	 * Sets key to 'value' returning previously associated value (alias for {@link CountIntMap#put(Object, Integer)}).
49  	 * @param key
50  	 * @param value
51  	 * @return
52  	 */
53  	public int set(KEY key, int value) {
54  		return counts.put(key, value);
55  	}
56  	
57  	/**
58  	 * Increase 'key' +1 returning previous value.
59  	 * @param key
60  	 * @return
61  	 */
62  	public int increase(KEY key) {
63  		return increase(key, 1);
64  	}
65  	
66  	/**
67  	 * Increase 'key' +amount returning previous value.
68  	 * @param key
69  	 * @return
70  	 */
71  	public int increase(KEY key, int amount) {
72  		return counts.put(key, get(key) + amount);
73  	}
74  
75  	/**
76  	 * Increase 'key' -1 returning previous value.
77  	 * @param key
78  	 * @return
79  	 */
80  	public int decrease(KEY key) {
81  		return increase(key, -1);
82  	}
83  	
84  	/**
85  	 * Increase 'key' -amount returning previous value.
86  	 * @param key
87  	 * @return
88  	 */
89  	public int decrease(KEY key, int amount) {
90  		return increase(key, -amount);
91  	}
92  
93  	/**
94  	 * Multiplies 'key' with amount returning previous value.
95  	 * @param key
96  	 * @return
97  	 */
98  	public int multi(KEY key, int amount) {
99  		return counts.put(key, get(key) * amount);
100 	}
101 
102 	@Override
103 	public boolean containsKey(Object key) {
104 		return counts.containsKey(key);
105 	}
106 
107 	@Override
108 	public boolean containsValue(Object value) {
109 		return counts.containsValue(value);
110 	}
111 
112 	@Override
113 	public boolean isEmpty() {
114 		return counts.isEmpty();
115 	}
116 
117 	@Override
118 	public Integer put(KEY key, Integer value) {
119 		return counts.put(key, value);
120 	}
121 
122 	@Override
123 	public void putAll(Map<? extends KEY, ? extends Integer> m) {
124 		counts.putAll(m);
125 	}
126 
127 	@Override
128 	public int size() {
129 		return counts.size();
130 	}
131 
132 }