使用带有通配符的通用地图时出现问题
我有一个返回 map
的方法,定义为:
public Map<String, ?> getData();
我不清楚该方法的实际实现,但是,当我尝试执行以下操作时:
obj.getData().put("key","value")
我收到以下编译时错误消息:
方法 put(String, capture#9-of ?) 在类型映射中 不适用于参数 (字符串,字符串)
有什么问题? String
不是任何类型吗?
提前致谢。
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:
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?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
的返回类型
与 The相同,
意味着返回的具体类型可以是
Map
。您无法将String
放入AnyClass
中,因此会出现错误。一个好的通用原则是不要在方法返回类型中使用通配符。
The return type of
is the same as
The means that the concrete type returned could be a
Map<String, AnyClass>
. You can't put aString
into anAnyClass
, hence the error.A good general principle is to not use wildcards in method return types.
通配符的意思是“值类型参数可以是任何东西” - 它不是意味着“你可以使用它,就好像它是你想要的任何东西一样”。换句话说,
Map
与Map
一样有效 - 但您不希望能够放置 String价值融入其中。如果您想要一个绝对可以接受字符串值的映射,您需要:
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 aMap<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
是Map
并不意味着任何东西都可以作为值添加。它表示 Map 对象可以具有任何扩展Object
的通用值类型。这意味着 Map 对象也可以是
HashMap
或HashMap
。因为编译器无法检查哪些值类型将被接受,所以他不会让你调用以值类型作为参数的方法。注意:
Map
将产生相反的效果:您始终可以使用 String 作为参数,但返回类型不清楚。Map<String, ?>
is a short form ofMap<String,? extends Object>
and doesn't mean that anything can be added as value. It says that the Map-object can have any generic value type extendingObject
.This means that the Map object can be a
HashMap<String, String>
or aHashMap<String, Integer>
as well. Because the compiler can't check which value types will be accepted, he won't let you call methods with the value type as a parameter.Note:
Map<String, ? super String>
will have the opposite effect: You can always use a String as parameter, but the return-type is unclear.试试这个:
Try this:
[编辑]这真的是错误的......我明白了。
我的第一个答案是:
But String extends Object... 虽然我认为 String 是一个基元。我学到了一些东西^^
[EDIT] This is really wrong... I understood.
My first answer was:
But String extends Object... while I thought String was a primitive. I learned something ^^