Problem using generic map with wildcard(使用带有通配符的通用映射的问题)
问题描述
我有一个返回 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>
这篇关于使用带有通配符的通用映射的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用带有通配符的通用映射的问题
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
