使用通配符通用映射的问题 [英] Problem using generic map with wildcard
问题描述
我有一个返回地图的方法
定义为:
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方法(字符串,捕获#9的?)
在类型地图
是不适用的参数
(字符串,字符串)
The method put(String, capture#9-of ?) in the type Map is not applicable for the arguments (String, String)
这是什么问题?为字符串
不是什么类型?
What is the problem? Is String
not of type anything?
先谢谢了。
推荐答案
通配符的意思是值类型参数可以是任何东西 - 它的不的意思是你可以使用这个,就好像它是你希望它是什么。换句话说,一个地图&LT;弦乐,UUID&GT;
有效期为地图&LT;弦乐,&GT;
- 但你不会希望能够把一个字符串值到它。
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>
这篇关于使用通配符通用映射的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!