View Javadoc

1   package cz.cuni.amis.utils.maps;
2   
3   import java.util.ArrayList;
4   import java.util.Collections;
5   import java.util.HashMap;
6   import java.util.List;
7   
8   /**
9    * Map containing lists of items. Whenever a list under some key is requested and does not exists,
10   * the HashMapList automatically creates new one.
11   * <p><p>
12   * The implementation is unsynchronized, created lists are synchronized (just iteration over list must
13   * be synchronized by the user as described in Java(tm) documentation).
14   * 
15   * @author Jimmy
16   *
17   * @param <KEY>
18   * @param <ITEM>
19   */
20  public class HashMapList<KEY, ITEM> extends HashMap<KEY, List<ITEM>>{
21  	
22  	/**
23  	 * Returns a list under a specific key in the map. If list does not exist, it
24  	 * automatically creates new (synchronized) one, inserts it into map and returns it.
25  	 */
26  	@Override
27  	public List<ITEM> get(Object key) {
28  		List<ITEM> list = super.get(key);
29  		if (list != null) return list;
30  		list = Collections.synchronizedList(new ArrayList<ITEM>());
31  		super.put((KEY)key, list);
32  		return list;
33  	}
34  	
35  	/**
36  	 * Add a new item at the end of the list under a specific key. If list does not exists,
37  	 * it automatically creates new (synchronized) one.
38  	 * @param key
39  	 * @param item
40  	 */
41  	public void add(KEY key, ITEM item) {
42  		get(key).add(item);
43  	}
44  	
45  	/**
46  	 * Remove returns the removed item, if item was non-existent, it returns empty list. 
47  	 * @param key
48  	 * @return
49  	 */
50  	@Override
51  	public List<ITEM> remove(Object key) {
52  		List<ITEM> list = super.remove(key);
53  		if (list != null) return list;
54  		return Collections.synchronizedList(new ArrayList<ITEM>(0));
55  	}
56  	
57  	/**
58  	 * Remove an item at 'index' from the list under a specific key. The list bounds are not checked.
59  	 * @param key
60  	 * @param index
61  	 * @return
62  	 */
63  	public ITEM remove(KEY key, int index) {
64  		return get(key).remove(index);
65  	}
66  	
67  	/**
68  	 * Returns first item from the list under a specific key. If the list is empty, returns null.
69  	 * @param key
70  	 * @return
71  	 */
72  	public ITEM peek(KEY key) {
73  		List<ITEM> list = get(key);
74  		if (list.size() > 0) return list.get(0);
75  		return null;
76  	}
77  	
78  	/**
79  	 * Removes first item from the list under a specific key.
80  	 * @param key
81  	 * @return
82  	 */
83  	public ITEM pull(KEY key) {
84  		return remove(key, 0);
85  	}
86  	
87  }