[英]Generics - How to transfer map to map with ? extends x?
Map<String, ? extends MyClass> map;//instantiate and put values somewhere
Map<String, MyClass> map2; //instantiate and put values somewhere.
Given the maps above, how to transfer from map
to map2
, and from map2
to map
using putAll()
, or achieve the putAll()
effect? 给定上面的地图,如何使用
putAll()
从map
转移到map2
以及从map2
转移到map
或实现putAll()
效果?
If I know the Class is InstanceClass
, can I somehow cast it to Map<String, InstanceClass>map;
如果我知道该类是
InstanceClass
,我可以以某种方式将其强制转换为Map<String, InstanceClass>map;
? ?
Map<String, ? extends MyClass> map;//instantiate and put values somewhere
The wildcard expression ? extends MyClass
通配符表达
? extends MyClass
? extends MyClass
signifies a producer, meaning that you can't add objects to it because you do not know what type of object the value of the map currently holds. ? extends MyClass
表示生产者,这意味着您无法向其添加对象,因为您不知道地图的值当前持有哪种类型的对象。 You can only read from it. 您只能从中阅读。
More info can be found in the following SO answers here and here . 更多信息可在下列SO答案被发现这里和这里 。
You can copy them entry-wise. 您可以按入口复制它们。 Here's an approach that uses
Map.forEach
: 这是一种使用
Map.forEach
的方法:
map.forEach(map2::put);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.