Why is this conversion invalid?

I would 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 invalid?

+2
source share
2 answers

Not valid, as if it were valid, you could add non-integer lists to ml .

Example (invalid):

 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 Map<String, ?> ml2 = ml; acting? This is because using a wildcard tells the compiler to prevent new elements from being added, i.e. ml2.put("strings", Arrays.asList("evil","string")); will not be allowed (the compiler does not perform type checking, it just sees a wildcard and knows that you should not call this method.

+7
source

Map<String, ?> Will take a map of strings for any object, List of Integer can be matched by this pattern. However, List of Integer does not match the list? (A list of any object), since the List of Integer can only accept Integer objects.

-1
source

Source: https://habr.com/ru/post/1259471/


All Articles