2015-05-29 97 views
1

這裏的第一篇文章參數...Java的:不能返回泛型集合延伸的返回類型

這是我定義泛型類:

public class TimeSeries<T extends Number> extends TreeMap<Integer, T>{ 
    ... 

    public Collection<Number> data() { 
     return this.values(); 
    } 
} 

上下文的位。 TimeSeries基本上是一種特定種類的TreeMap,其中鍵是整數,值是數字。

我的問題是數據的方法有以下錯誤打破:

error: incompatible types: Collection<T> cannot be converted to Collection<Number> 
    return this.values(); 
        ^
where T is a type-variable: T extends Number declared in class TimeSeries 

值方法只返回T的集合到底爲什麼我不能回到這一點的方法,如果我有特別聲明那T擴展數字?

在此先感謝。

+0

'this.values()'的類型是什麼? –

+0

退貨類型爲:收藏

回答

4

你必須返回任何這些類型的:

public Collection<? extends Number> data() { 
    return this.values(); 
} 

或其

public Collection<T> data() { 
    return this.values(); 
} 

這樣的想法:

TimeSeries<Integer> series = new TimeSeries<>(); 

// You want this: 
Collection<Number> data = series.data(); 

// Oops, compiles, but not an Integer: 
data.add(Long.valueOf(42)); 

的更多信息:

+0

太棒了!說得通。謝謝盧卡斯 –

+0

在這種情況下提及並不是絕對必要的。因此,你可以指定它沒有generic: 'public class TimeSeries extends TreeMap ' – nesteant

+0

@nesteant:這是不正確的。 OP *希望*具有通用的TimeSeries 類型,這非常合理。 –

1

如果您想返回Collection<Number>,您可以使用Collections.unmodifiableCollection,使一個只讀視圖在Collection<T>

public Collection<Number> data() { 
    return Collections.unmodifiableCollection(this.values()); 
} 

unmodifiableCollection和它的堂兄弟Collections類非常方便將只讀視圖作爲子類型集合的超類型集合。

+0

@LukasEder你使用的是什麼版本的java?不可修改收藏的簽名是'靜態'收藏不可修改收藏(收藏 c)'。它編譯我嘗試過的每個Java版本,並且工作得很好。 – Misha

+0

有趣,我的壞。我似乎遇到了Eclipse編譯器問題。將驗證,但你的解決方案似乎很好 –