使用带有通配符的通用映射的问题
我有一个返回 map
的方法,定义为:
I have a method that returns a map
defined as:
public Map<String, ?> getData();
这个方法的实际实现我不清楚,但是,当我尝试这样做时:
The actual implementation of this method is not clear to me, but, when I try to do:
obj.getData().put("key","value")
我收到以下编译时错误消息:
I get following compile time error message:
方法 put(String, capture#9-of ?)在类型地图不适用于论点(字符串,字符串)
The method put(String, capture#9-of ?) in the type Map is not applicable for the arguments (String, String)
有什么问题?String
不是什么类型的吗?
What is the problem? Is String
not of type anything?
提前致谢.
推荐答案
通配符的意思是值类型参数可以是任何东西"——它不的意思是你可以像使用它一样使用它是你想要的任何东西".换句话说, Map<String, UUID>
作为 Map
The wildcard means "the value type parameter could be anything" - it doesn't mean "you can use this as if it were anything you want it to be". In other words, a Map<String, UUID>
is valid as a Map<String, ?>
- but you wouldn't want to be able to put a String value into it.
如果你想要一个绝对可以接受字符串值的地图,你想要:
If you want a map which can definitely accept string values, you want:
Map<String, ? super String>
相关文章