使用带有通配符的通用映射的问题 [英] Problem using generic map with wildcard

查看:26
本文介绍了使用带有通配符的通用映射的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 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 是有效的 - 但您不希望能够放置 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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆