List<Object> a = null;
List<?> b = null;
b = a; // Can be assigned
List<List<Object>> a = null;
List<List<?>> b = null;
b = a; // Cannot be assigned
Could you explain why Java does not allow the second case? What are the side-effects of the case and underlying philosophy?
I have seen Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic? but this question is different because there is the inheritance relationship between Dog
and Animal
but here is no relationship between the wildcard type ?
and Object
. Wildcard type represents 'some unknown type,' which means List<?>
can be List<Object>
in the runtime: Intuitively speaking, here List<?>
is a candidate Dog
(Not Animal
), there List<Object>
is a Dog
.
List<String>
cannot be assigned to List<Object>
, which is the same case of the previous question and explained there why it is not allowed. However, List<String>
can be assigned to List<?>
, which is the case I am asking and different from the previous case. Since the assignment is allowed, I expected List<List<Object>>
can be assigned to List<List<?>>
.
>` for example.
– Sweeper Jul 19 '23 at 06:49> b = new ArrayList<>(); List
– freddy Jul 19 '23 at 07:08