0

Let: B extends A;

Can somebody tell me why this code:

List<Class<? extends A>> l = Arrays.asList(B.class);

Throws me the following error when trying to compile:

error: incompatible types: List<Class<B>> cannot be converted to List<Class<? extends A>>

while this code:

ArrayList<Class<? extends A>> l = new ArrayList<Class<? extends A>>();
l.add(B.class);

works perfectly fine?

PeterErnsthaft
  • 375
  • 5
  • 14

1 Answers1

2

As per documentation the Arrays.asList(..) method takes as its parameter variable(s) of the same type and returns the list of that type.

public static <T> List<T> asList(T... a)

If Class<B> is bond to type T then the method return type is List<Class<B>> which is NOT type List<Class<? extends A>> as expected. Thus the compile error occurs.

It can be fixed by adding the explicit cast as below:

List<Class<? extends A>> l = Arrays.<Class<? extends A>>asList(B.class);


EDITED
As mentioned by Sotirios Java 8 has resolved that tedious issue with introduction of poly expression explained here.

Community
  • 1
  • 1
MaxZoom
  • 7,619
  • 5
  • 28
  • 44