当方法的签名定义为Collection <class>时,为什么方法不能采用Collection <subClass>

Ank*_*kur 6 java collections inheritance

我有一个方法,它采用SResource对象列表

public static List<STriple> listTriples(List<SResource> subjects){
//... do stuff
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能这样做

List<IndexResource> resultsAsList = new ArrayList<IndexResource>();
    resultsAsList.addAll(allResults.keySet()); // I could possible not use lists and just use sets and therefore get rid of this line, but that is a different issue
List<STriple> triples = new ArrayList<STriple>();
    triples = TriplesDao.listTriples(resultsAsList);
Run Code Online (Sandbox Code Playgroud)

(编译器告诉我必须triples使用SResource对象.)

当IndexResource是SResource的子类时

public class IndexResource extends SResource{ 
// .... class code here
}
Run Code Online (Sandbox Code Playgroud)

我本以为这是可能的,所以也许我做错了什么.如果你建议,我可以发布更多代码.

dle*_*lev 23

你可以使用通配符来做到这一点:

public static List<STriple> listTriples(List<? extends SResource> subjects){
    //... do stuff
}
Run Code Online (Sandbox Code Playgroud)

新声明使用有界通配符,表示泛型参数将是一个SResource或扩展它的类型.

作为接受List<>这种方式的交换,"做东西"不能包括插入subjects.如果您只是从subjects方法中读取,那么此更改应该可以获得您想要的结果.

编辑:要了解为什么需要通配符,请考虑这个(Java中的非法)代码:

List<String> strings = new ArrayList<String>();
List<Object> objList = string; // Not actually legal, even though string "is an" object
objList.add(new Integer(3)); // Oh no! We've put an Integer into an ArrayList<String>!
Run Code Online (Sandbox Code Playgroud)

这显然不是类型安全的.但是,使用wilcards,您可以这样做:

List<String> strings = new ArrayList<String>();
string.add("Hello");
List<? extends Object> objList = strings; // Works!
objList.add(new Integer(3)); // Compile-time error due to the wildcard restriction
Run Code Online (Sandbox Code Playgroud)


San*_*rma 6

你不能这样做,因为泛型不是"协变",即a List<Integer>不是子类,List<Number>虽然Integer是子类Number.