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>
这篇关于使用带有通配符的通用映射的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用带有通配符的通用映射的问题


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01