Why doesn’t this work?
public class FooImpl implements Foo { /* ... */ }
public class Main {
public static <T> Collection<T> getList(Class<? extends T> itemClass) { /* ... */ }
public static void main(String[] args) {
Collection<Foo> foos = getList(FooImpl.class);
}
}
On the line where foos is declared, I’m getting “Incompatible types. Required: Collection<Foo>, found: Collection<FooImpl>” error. Any idea why?
Try this :
When you create your
getList()method, it says that it will be Typed with T. And it also says that it will need a parameter of a subtype of T (a class of subtype of T to be precise).As you never specify what will T be, getList suppose that it will be
FooImplsogetList()returns a Collection ofFooImpl.With the solution I gave you, you specify that T is
Foo, so the parameter will need to be a subtype ofFoo.FooImplfor example.Resources :