1
2
3
4
5
6 package org.glassbox.util;
7
8 import java.util.HashMap;
9 import java.util.List;
10 import java.util.LinkedList;
11
12 /***
13 A HashMap which maps keys to lists of values.
14 This implementation is not thread-safe.
15 */
16 public class HashMapOfLists extends HashMap {
17 /***
18 Get the list mapped by the specified key.
19 This method will never return <code>null</code>.
20 If no value is mapped by the specified key, an empty list will be returned.
21 */
22 public List getList(Object key) {
23 List list = (List)super.get(key);
24 if (list==null) {
25 list = new LinkedList();
26 super.put(key, list);
27 }
28 return list;
29 }
30
31 /***
32 Add a value to the list of values mapped by the specified key.
33 @return The specified value.
34 */
35 public Object put(Object key, Object value) {
36 List list = getList(key);
37 list.add(value);
38 return value;
39 }
40
41 /***
42 Remove the specified value from the list mapped by the specified key.
43 @return True if the specified value was an item of the list mapped by the specified key.
44 */
45 public boolean remove(Object key, Object value) {
46 List list = getList(key);
47 if (list!=null) return list.remove(value);
48 else return false;
49 }
50 }