2013-02-28 159 views
-1

我想了解爲什麼這段代碼不會編譯。
我有一個類實現一個接口。由於某種原因,最後的方法不會編譯。Java拋出與SortedSet異常

它不會簡單地允許我將集合轉換爲集合,但確實允許它返回單個對象。

有人可以向我解釋爲什麼這是?謝謝。

public class Testing2 { 

    public SortedSet<ITesting> iTests = new TreeSet<ITesting>(); 
    public SortedSet<Testing> tests = new TreeSet<Testing>(); 

    public ITesting iTest = null; 
    public ITesting test = new Testing(); 

    // Returns the implementing class as expected 
    public ITesting getITesting(){ 
     return this.test; 
    } 

    // This method will not compile 
    // Type mismatch: cannot convert from SortedSet<Testing> to SortedSet<ITesting> 
    public SortedSet<ITesting> getITests(){ 
     return this.tests; 
    } 

} 
+0

你會編輯你的問題,包括確切的編譯器信息嗎?編輯:另外,它看起來像測試實現ITesting? – 2013-02-28 21:44:02

+0

是的,對不起。測試實現ITesting – Marley 2013-02-28 21:48:05

+0

看起來像http://stackoverflow.com/questions/897935/when-do-java-generics-require-extends-t-instead-of-t-and-is-there-any-down的副本 – 2013-02-28 21:49:36

回答

6

簡單地說,SortedSet<Testing>不是一個SortedSet<ITesting>。例如:

SortedSet<Testing> testing = new TreeMap<Testing>(); 
// Imagine if this compiled... 
SortedSet<ITesting> broken = testing; 
broken.add(new SomeOtherImplementationOfITesting()); 

現在你SortedSet<Testing>將包含的元素,其不是一個Testing。那會很糟糕。

可以做的是這樣的:

SortedSet<? extends ITesting> working = testing; 

...因爲你只能得到價值出一套

所以這應該工作:

public SortedSet<? extends ITesting> getITests(){ 
    return this.tests; 
} 
+0

謝謝。這很有幫助! – Marley 2013-02-28 21:48:30

0

你在你的declartion有一個錯字:

public SortedSet<Testing> tests = new TreeSet<Testing>(); 

,如果你想返回ITesting的方法,或者你需要的方法應該是ITesting有返回:

SortedSet<Testing> 
0

我想你想用這個代替:

public SortedSet<Testing> getTests(){ 
    return this.tests; 
} 

現在你試圖返回tests,它被聲明爲SortedSet<Testing>而不是SortedSet<ITesting>

1

假設ITestingTesting的超級類型。 通用類型不是多態的。因此SortedSet<ITesting>不是超級類型SortedSet<Testing>多態性根本不適用於泛型類型。你可能需要使用通配符? extends ITesting作爲你的返回類型。

public SortedSet<? extends ITesting> getITests(){ 
    return this.tests; 
}