5
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>

while,

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

Although i know the type erasure, i do not the reason of compiling failed!

Help, thx!

xiaok
  • 55
  • 3
  • 1
    related question: http://stackoverflow.com/questions/306713/java-collections-emptylist-returns-a-listobject – Colin D May 25 '12 at 12:38

3 Answers3

7

Try this:

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

In the first example you are not allowing Java to capture the <T> in public static <T> List<T> Collections.emptyList() since you are not assigning it directly to the var. Java's type inference is very weak and is not able to see through the conditional operator. In the second example you have a straightforward situation and T is successfully captured into Integer.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

The reason the second works is that the compiler is able to figure out the exact type needed from the type of the variable where the result is stored. OTOH Java's type caclulation is not powerful enough to do the same in the first case

Attila
  • 28,265
  • 3
  • 46
  • 55