[英]Putting into a Map<String, ?>
So I have a Map that has some values in it being passed into a method: 所以我有一个Map,它有一些值传递给一个方法:
public String doThis(Map<String, ?> context){
.....
}
And I'm trying to insert an addition attribute to this Map 我正在尝试向此Map添加一个附加属性
String abc="123";
context.put("newAttr",abc);
But I am getting this error: 但是我收到了这个错误:
The method put(String, capture#8-of ?) in the type Map is not applicable for the arguments (String, String)
方法put(String,capture#8-of?)在Map类型中不适用于参数(String,String)
Is there anyway to perform this put without "cloning" the Map? 无论如何在没有“克隆”地图的情况下执行此放置?
If you want to put values of type X into a generic Map
you need to declare the Map
as Map<String, ? super X>
如果要将X类型的值放入通用
Map
,则需要将Map
声明为Map<String, ? super X>
Map<String, ? super X>
. Map<String, ? super X>
。 In your example X is String
, so: 在您的示例中,X是
String
,因此:
public String doThis(Map<String, ? super String> context){
.....
}
Map<String, ? super X>
Map<String, ? super X>
means: a map with keys of type String
and values of a type which is X or a super-type of X. All such maps are ready to accept String
instances as keys and X instances as values. Map<String, ? super X>
表示:具有String
类型的键的映射,以及X的类型或X的超类型的值。所有这些映射都准备接受String
实例作为键,X实例作为值。
Remember PECS (Producer Extends, Consumer Super). 记住PECS(Producer Extends,Consumer Super)。 You have a consumer (putting in), therefore it cannot be
extends
. 你有一个消费者(投入),因此它不能
extends
。
Surprisingly we can convert this map into an easier to use form. 令人惊讶的是,我们可以将此地图转换为更易于使用的形式。 Just with this simiple syntax:
(Map<String, ObjectOrSth>)unfriendlyMap
. 只需使用这种simiple语法:(
(Map<String, ObjectOrSth>)unfriendlyMap
。
// Let's get this weird map.
HashMap<String, String> mapOrig = new HashMap<String, String>();
Map<String, ?> mapQuestion = (Map<String, ?>)mapOrig;
//mapQuestion.put("key2", "?"); // impossible
// Convert it to almost anything...
Map<String, String> mapStr2 = (Map<String, String>)mapQuestion;
mapStr2.put("key2", "string2");
assertThat(mapOrig.get("key2")).isEqualTo("string2");
Map<String, Object> mapObj = (Map<String, Object>)mapQuestion;
mapObj.put("key3", "object");
assertThat(mapOrig.get("key3")).isEqualTo("object");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.