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?
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?
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.
Map<String, ?>
will take a map of Strings to any object, List of Integer can be matched by this wildcard. However, List of Integer does not match List of ? (List of any object), as List of Integer can only take Integer objects.