How to declare a map with variable generics?

Viewed 14609

I have a Map whose keys are of generic type Key<T>, and values are of type List<T>. If the key is an instance of Key<String>, the value must be a List<String>, and the same rule applies to any other key-value pairs. I have tried the following but it does not compile:

Map<T, List<T>> map;

At present I have to declare it with "partial" generics:

Map<Object, List> map;

I know this is bad but I currently have no better choice. Is it possible to use generics in this situation?

UPDATE

Maybe I didn't express my problem clearly. I want a map that is able to:

map.put(new Key<String>(), new ArrayList<String>());
map.put(new Key<Integer>(), new ArrayList<Integer>());

And the following code should not compile:

map.put(new Key<String>(), new ArrayList<Integer>());

The key and value should always have the same generic type while the generic type can be any, and obviously extending a map does not meet my requirement.

2 Answers
Related