java 如何声明带有可变泛型的映射?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11498069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare a map with variable generics?
提问by Zhao Yi
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
它的键是泛型类型Key<T>
,值是类型List<T>
。如果键是 的实例Key<String>
,则值必须是 a List<String>
,并且相同的规则适用于任何其他键值对。我尝试了以下操作,但无法编译:
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.
键和值应该始终具有相同的泛型类型,而泛型类型可以是任意的,显然扩展映射不符合我的要求。
采纳答案by Geoff Reedy
I'm not aware of any existing library that does precisely this but it is not too hard to implement yourself. I've done something similar a few times in the past. You cannot use the standard Map interface but you can use a hash map inside to implement your class. To start, it might look something like this:
我不知道有任何现有的库可以做到这一点,但是自己实现并不难。我过去做过几次类似的事情。您不能使用标准的 Map 接口,但您可以在内部使用哈希映射来实现您的类。首先,它可能看起来像这样:
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>());
}
}
回答by Brad
This is what you want:
这就是你想要的:
public class Test<T> extends HashMap<T, List<T>>
{
}
If you don't want a HashMap as the super class then change it to whatever concrete class you want.
如果您不希望 HashMap 作为超类,则将其更改为您想要的任何具体类。