View Javadoc

1   package cz.cuni.amis.utils.maps;
2   
3   import java.util.Collections;
4   import java.util.HashMap;
5   import java.util.HashSet;
6   import java.util.Set;
7   
8   /**
9    * Map containing sets. Whenever a set under some key is requested and does not exists,
10   * the HashMapSet automatically creates new one.
11   * <p><p>
12   * The implementation is unsynchronized, created sets are synchronized (just iteration over the set 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 HashMapSet<KEY, ITEM> extends HashMap<KEY, Set<ITEM>> {
21  	
22  	/**
23  	 * The get method ensures that the requested set under primaryKey always exists!
24  	 * 
25  	 * @param primaryKey must be instance of PRIMARY_KEY
26  	 */
27  	@Override
28  	public Set<ITEM> get(Object primaryKey) {
29  		Set<ITEM> set = super.get(primaryKey);
30  		if (set != null) return set;
31  		set = Collections.synchronizedSet(new HashSet<ITEM>());
32  		super.put((KEY)primaryKey, set);
33  		return set;
34  	}
35  	
36  	/**
37  	 * Adds the item into the set under the key.
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 set. 
47  	 * @param primaryKey
48  	 * @return
49  	 */
50  	@Override
51  	public Set<ITEM> remove(Object key) {
52  		Set<ITEM> set = super.remove(key);
53  		if (set != null) return set;
54  		return Collections.synchronizedSet(new HashSet<ITEM>());
55  	}
56  	
57  	/**
58  	 * Removes the item from the set under the key.
59  	 * @param key
60  	 * @param item
61  	 */
62  	public boolean remove(KEY key, ITEM item) {
63  		return get(key).remove(item);
64  	}
65  	
66  	/**
67  	 * Tests whether an 'item' is inside the set under 'key'.
68  	 * @param key
69  	 * @param item
70  	 * @return
71  	 */
72  	public boolean contains(KEY key, ITEM item) {
73  		return get(key).contains(item);
74  	}
75  	
76  }