julaudo julaudo - 1 year ago 108
Java Question

Why is this conversion not valid?

I'd like to use a map with various lists as values :

Map<String, List<Integer>> ml;
Map<String, ?> ml2 = ml; // OK
Map<String, List<?>> ml3 = ml; // Type mismatch

Why is the last line not valid?

Answer Source

It's not valid because if it was valid you'd be able to add non-integer lists to ml as well.

Example (not valid):

Map<String, List<Integer>> ml;
Map<String, List<?>> ml3 = ml; 

ml3.put("strings", Arrays.asList("evil","string"));

List<Integer> l = ml.get("strings"); //see how this is going to fail?

Why is Map<String, ?> ml2 = ml; valid? That's because the use of a wildcard tells the compiler to not allow adding new elements, i.e. ml2.put("strings", Arrays.asList("evil","string")); would not be allowed (the compiler doesn't do a type check, it just sees the wildcard and knows you must not call that method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download