簡體   English   中英

為什么方法不能采用Collection <subClass> 當方法的簽名定義為Collection時 <class>

[英]Why can't a method take a Collection<subClass> when the method's signature is defined as Collection<class>

我有一個方法,它采用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);

(編譯器告訴我,我必須使用triples使用SResource對象。)

當IndexResource是SResource的子類時

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

我原本以為這是可能的,所以也許我做錯了什么。 如果你建議,我可以發布更多代碼。

你可以使用通配符來做到這一點:

public static List<STriple> listTriples(List<? extends SResource> subjects){
    //... do stuff
}

新聲明使用有界通配符 ,表示泛型參數將是SResource或擴展它的類型。

以這種方式接受List<>交換,“do stuff”不能包括插入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>!

這顯然不是類型安全的。 但是,使用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

你不能這樣做,因為仿制葯不是“協變”List<Integer>不是一個子類的List<Number>雖然Integer是一個子類的Number

對於那些無法添加通配符的人,這應該可行。

List<Integer> list = new ArrayList<Integer>();
new ArrayList<Number>(list);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM