Stumbled upon incompatible types error cause of which I don't understand.
Why is this piece of code wrong?
List<List<String>> a = new ArrayList<>();
List b = a; // is ok
List<List> c = a; // incompatible types
List<List>
is implicitly
List<List<Object>>
which is not a parent of
List<List<String>>
the reason why it succeeds in the first case is because of Type Inference. The compiler will essentially check which type is needed for the expression to make sense and it will generate
List<List<String>> a = b;
In the second case it will default to
List<List<Object>> a = b // which does not compile
Writing
List b = a;
Doesn't involves generics. It defines a raw List type named b which can take any object as it's element.
Don't compare it with
List<List> c = a;
as it involves generics and that's why compiler will enforce type compatibility checking here.
Short answer: because your c
list contains a list with all kind of objects.
For example you can also add Integer
objects.
And a
list can contains only String
objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.