微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/java/128465.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐