为什么某个方法不能使用Collection< subClass>当方法的签名被定义为Collection< class> [英] Why can't a method take a Collection<subClass> when the method's signature is defined as Collection<class>
问题描述
我有一个方法,它接受一个SResource对象的列表。
I have a method that takes a list of SResource objects
public static List<STriple> listTriples(List<SResource> subjects){
//... do stuff
}
$ b b
为什么我不能这样做
Why can't I do this
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对象。)
(The compiler tells me I have to make triples
use SResource objects.)
当IndexResource是SResource的子类时
When IndexResource is a subclass of SResource
public class IndexResource extends SResource{
// .... class code here
}
我本以为这是可能的,所以也许我做错别的东西。我可以发布更多的代码,如果你建议它。
I would have thought this has to be possible, so maybe I am doing something else wrong. I can post more code if you suggest it.
推荐答案
您可以使用:
You can do it, using wildcards:
public static List<STriple> listTriples(List<? extends SResource> subjects){
//... do stuff
}
b $ b
新声明使用一个有界通配符,其中通用参数将是 SResource
The new declaration uses a bounded wildcard, which says that the generic parameter will be either an SResource
, or a type that extends it.
以这种方式接受列表<>
包括插入主题
。如果你只是从方法中的 subject
中读取,那么这个更改应该会得到你想要的结果。
In exchange for accepting the List<>
this way, "do stuff" can't include inserting into subjects
. If you're just reading from the subjects
in the method, then this change should get you the results you want.
EDIT :要查看为什么需要通配符,请考虑这是(Java中的非法)代码:
EDIT: To see why wildcards are needed, consider this (illegal in Java) code:
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,您可以执行此操作:
That's obviously not typesafe. With wilcards, though, you can do this:
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
这篇关于为什么某个方法不能使用Collection< subClass>当方法的签名被定义为Collection< class>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!