Generic Incompatible Types

I came across incompatible types of errors, the cause of which I do not understand.

Why is this code incorrect?

List<List<String>> a = new ArrayList<>(); List b = a; // is ok List<List> c = a; // incompatible types 
+5
source share
4 answers

It is described here . Supertype compatibility only works at the "external" level, but not "inside" by type parameters. This is not intuitive, but how it works ... Also, List is a raw type, and it behaves somewhat differently than List<Object> - which is described here .

+7
source
 List<List> 

implicitly

List<List<Object>>

which is not a parent

 List<List<String>> 

the reason he succeeds in the first case is type inference. The compiler essentially checks what type is needed so that the expression makes sense, and it will generate

 List<List<String>> a = b; 

In the second case, the default will be

 List<List<Object>> a = b // which does not compile 
+3
source

Spelling

 List b = a; 

Does not contain generics. It defines the type of raw list named b, which can take any object as its element.

Do not compare it with

 List<List> c = a; 

as it includes generalizations and that the compiler will conduct type compatibility checks here.

+3
source

Short answer: because your list c contains a list with all types of objects.
For example, you can also add Integer objects.
A list a can contain only String objects.

+2
source

Source: https://habr.com/ru/post/1201909/


All Articles