This following code compiles ok:
List<String> strList = List.of("foo", "bar");
List<?> genList = strList;
But a nested list does not:
List<List<String>> strList = List.of(List.of("foo", "bar"));
List<List<?>> genList = strList;
Why is this? And if I need to do this, what is the 'correct' way to do it?
The use case is that I have a method that returns one of a number of different collections where the element type is itself generic with a different defined type for each possible return value, where the return value is dependent on the argument passed in. At the moment, as a workaround, I am assigning the result to a variable where the type is the collection type with a wildcard (i.e. List<?>>
) and performing the full cast at the end of the method (i.e. return (List<List<T>>) result
), where the return
>` is not a `List
>` for the same reason as `Integer` is a `Number` but a `List` is not a `List`, because you could add a `Long` to a `List` which would be horrible if it actually refers to your `List`. Just generalize it; a `List` is not a `List` and it doesn’t matter whether “`Sub` and `Super`” are “`Integer` and `Number`” or “`List` and `List>`”