Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics incompatible types

Tags:

java

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
like image 943
Alex Orlov Avatar asked Sep 05 '14 13:09

Alex Orlov


People also ask

What are not allowed for generics?

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.

Why generics are not supported to primitive data 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.

Why primitive data types are not allowed in Java generics?

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.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.


2 Answers

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.

like image 175
sfThomas Avatar answered Sep 30 '22 21:09

sfThomas


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.

like image 44
Vaibhav Raj Avatar answered Sep 30 '22 21:09

Vaibhav Raj