0
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;?

theAnonymous
  • 2,026
  • 2
  • 21
  • 50
  • I must be missing something, because `map2.putAll(map)` seems like it would work. You can't do the converse, because it is not type safe. – Andy Turner Nov 17 '18 at 13:48

2 Answers2

1

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

The wildcard expression ? 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.

Nicholas K
  • 14,118
  • 7
  • 25
  • 49
0

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

map.forEach(map2::put);
ernest_k
  • 39,584
  • 5
  • 45
  • 86