Could you explain why the first one does not work?
import java.util.ArrayList;
import java.util.List;
public class MyClass {
private <T extends Object> List<Class<T>> getList1() {
return new ArrayList<>();
}
private <T extends Object> List<Class<T>> getList2(Class<T> cls) {
List<Class<T>> list = new ArrayList<>();
list.add(cls);
return list;
}
private List<Class<? extends Object>> getList3() {
return new ArrayList<>();
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
// 1. Not OK - The method add(Class<Object>) in the type List<Class<Object>> is not applicable for the arguments (Class<String>)
myClass.getList1().add(String.class);
// 2. OK
myClass.getList2(String.class);
// 3. OK
myClass.getList3().add(String.class);
}
}
I thought getList1()
is returning a List
of classes those extend from Object
, and String
is one of those?
And no this is not a duplicated question (at least not to the one being linked). If I really defined a List of Object, of course I don't want it to take a List of String. But here I am accepting a List of Object plus those extending from Object, so the question is why didn't it accept String in the first case.