Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use addAll with generic collection?

Tags:

java

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?

like image 268
Pinch Avatar asked Nov 11 '22 22:11

Pinch


1 Answers

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.

like image 199
jilt3d Avatar answered Nov 14 '22 21:11

jilt3d