I wanted to create a Map of Collections in Java, so I can do something like
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
Collection c = new Collection();
c.add(value);
put(key, value);
}
}
I tried to do this with something like
public class CollectionMap<K, C extends Collection<V>> extends HashMap<K, C>
but the compiler complains about the part <V>, and still there will be the problem of creating a proper new collection.
At the moment, I have created two classes: SetMap, which look like
1: public class SetMap<K, V> extends HashMap<K, Set<V>> {
2:
3: public void add(K key, V value) {
4: if (containsKey(key)) {
5: get(key).add(value);
6: } else {
7: Set<V> list = new HashSet<V>();
8: list.add(value);
9: put(key, list);
10: }
11: }
12:
13: }
and the ListMap looks pretty much the same except line 7 where I create a new ArrayList. Such duplication is small enough to be tolerated, but the question remains, is such "nested generics" possible in Java?
EDIT:
As erickson said , the solution is in <A, B extends Something<A>>, not just<B extends Something<A>>
so the code may look something like
public abstract class CollelctionMap<K, V, C extends Collection<V>> extends HashMap<K, C> {
protected abstract C newCollection();
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
C c = newCollection();
c.add(value);
put(key, c);
}
}
}
and ListMap and SetMap provide only the appropriate collection