Puzzle Collections.emptyList ()

int j = 0; List<Integer> i = j > 0 ? Collections.emptyList() : new ArrayList<Integer>(); // compiler error:cannot convert from List<capture#1-of ? extends Object> to List<Integer> 

then,

 List<Integer> li = Collections.emptyList(); // it works 

Although I know type erasure, I cannot explain that compilation failed!

Help, thanks!

+4
source share
3 answers

Try the following:

 List<Integer> i = j > 0 ? Collections.<Integer>emptyList() : new ArrayList<Integer>(); 
+7
source

In the first example, you do not allow Java to capture <T> in public static <T> List<T> Collections.emptyList() , since you do not assign it directly to var. Java type inference is very weak and cannot see through a conditional statement. In the second example, you have a simple situation, and T successfully captured in Integer .

+2
source

The reason the second one works is because the compiler is able to determine the exact type needed for the type of variable in which the result is stored. OTOH Java type caclulation is not efficient enough to do the same in the first case

0
source

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


All Articles