简体   繁体   中英

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?

If I know the Class is InstanceClass , can I somehow cast it to Map<String, InstanceClass>map; ?

Map<String, ? extends MyClass> map;//instantiate and put values somewhere

The wildcard expression ? 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. You can only read from it.

More info can be found in the following SO answers here and here .

You can copy them entry-wise. Here's an approach that uses Map.forEach :

map.forEach(map2::put);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM