Why does
List<Map<String, Object>> a, b;
a.addAll(b);
compile
But
List<? extends Map<String, ?>> a, b;
a.addAll(b);
does not.
How to make the latter compile?
Imagine that CustomHashMap
extends HashMap
and you initialize a
like following:
List<CustomHashMap<String, String> list = new ArrayList<CustomHashMap<String, String>>();
List<? extends Map<String, ?>> a = list;
if you were able to to add entries to a
...
a.add(new HashMap<String, String>());
...you would encounter this strange situation
CustomHashMap<String, String> map = list.get(0); // you would expect to get CustomHashMap object but you will get a HashMap object instead
In other words, you don't know the actual type of you Map (when you say ? extends Map), everything you know is that it is a some subtype of Map and you can not add arbitrary objects to the List because you need to ensure that there is a supertype for the added object. But you can't since the exact type of the Map is unknown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With