How to declare a map with variable generics?

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

 Map<T, List<T>> map; 

Currently, I have to declare it using "partial" generics:

 Map<Object, List> map; 

I know this is bad, but currently I have no better choice. Can generics be used in this situation?

UPDATE

Perhaps I did not clearly express my problem. I want a card that is capable of:

 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 must always have the same general type, while the general type can be any, and obviously the map extension does not meet my requirement.

+8
java generics map
source share
2 answers

I do not know of any existing library that does just that, but it’s not too difficult to realize myself. I have done something similar several times in the past. You cannot use the standard map interface, but you can use the hash map internally to implement your class. For starters, it might look something like this:

 public class KeyMap { public static class Key<T> { } private final HashMap<Object,List<?>> values = new HashMap<Object,List<?>>(); public <T> void put(Key<T> k, List<T> v) { values.put(k, v); } public <T> List<T> get(Key<T> k) { return (List<T>)values.get(k); } public static void main(String[] args) { KeyMap a = new KeyMap(); a.put(new Key<String>(), new ArrayList<String>()); a.get(new Key<Integer>()); } } 
+7
source share

Is this what you want:

 public class Test<T> extends HashMap<T, List<T>> { } 

If you do not want the HashMap to be a superclass, change it to any specific class that you want.

+4
source share

All Articles