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
Cannot Use Casts or instanceof With Parameterized Types. Cannot Create Arrays of Parameterized Types. Cannot Create, Catch, or Throw Objects of Parameterized Types. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.
Type safety is verified at compile time, and runtime is unfettered by the generic type system. In turn, this imposed the restriction that generics could only work over reference types, since Object is the most general type available, and it does not extend to primitive types.
Generic type arguments are constrained to extend Object , meaning that they are not compatible with primitive instantiations unless boxing is used, undermining performance. With the possible addition of value types to Java (subject of a separate JEP), this restriction becomes even more burdensome.
A Generic class can have muliple type parameters.
It is described here.
Supertype compatibility works only on the 'outer' level, but not 'inside' across the type parameters. It is not intuitive, but that's how it works...
In addition, List
is a raw type, and it behaves slightly differently than List<Object>
- which is described here.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With