java – 当方法的签名定义为Collection时,为什么方法不能采用Collection

我有一个方法,它采用SResource对象列表
public static List<STriple> listTriples(List<SResource> subjects){
//... do stuff
}

为什么我不能这样做

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);

(编译器告诉我,我必须使用三元组来使用SResource对象.)

当IndexResource是SResource的子类时

public class IndexResource extends SResource{ 
// .... class code here
}

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

解决方法

您可以使用 wildcards执行此操作:
public static List<STriple> listTriples(List<? extends SResource> subjects){
    //... do stuff
}

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

作为接受List<>的交换.这样,“做东西”不能包括插入主题.如果您只是阅读方法中的主题,那么此更改应该可以获得您想要的结果.

编辑:要了解为什么需要通配符,请考虑这个(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>!

这显然不是类型安全的.但是,使用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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...