2012-07-26 149 views
1

我有一個關於Java中的genrics(可能很簡單)的問題。我有以下類:構造函數中的泛型Java類型錯誤

public class ValueCollection<Y> implements Collection<Y> 
{ 
    private Set<Entry<?, Y>> entries; 

    public ValueCollection(Set<Entry<?, Y>> entries) 
    { 
     this.entries = entries; 
    } 
    ... 
} 

當我這樣調用構造函數:

return new ValueCollection<V>(entries); 

我得到以下編譯器錯誤:

The constructor ValueCollection<V>(Set<Map.Entry<K,V>>) is undefined 

如果我改變我的同班同學這樣的:

public class ValueCollection<X, Y> implements Collection<Y> 
{ 
    private Set<Entry<X, Y>> entries; 

    public ValueCollection(Set<Entry<X, Y>> entries) 
    { 
     this.entries = entries; 
    } 
    ... 
} 

and my cons這個工程師打電話給:

return new ValueCollection<K, V>(this.entries()); 

編譯錯誤消失。我只是想知道爲什麼會這樣。謝謝您的幫助!

+0

如果你在第一種情況下用'new ValueCollection (entries)'調用構造函數怎麼辦?你的第一堂課只有一個類型參數。 – millimoose 2012-07-26 18:54:08

回答

2

Set<Entry<?, V>>要麼與任何密鑰類型和值的類型的一組條目的V與一些特定但未知的密鑰類型和K值類型V一組條目。由於後者,編譯器會拒絕您最初的構造函數調用。

Set<? extends Entry<?, V>>一組與任何密鑰類型和值類型V條目的條目。這正是你想要的,重新定義你的構造函數參數類型爲Set<? extends Entry<?, V>>

您可以使用this.entries = Collections.unmodifiableSet(entries)this.entries = new HashSet<Entry<?, V>>(entries)將參數分配給您的字段。右側都產生一個Set<Entry<?, V>>,其方式使編譯器相信它意味着具有任何鍵類型和值類型的條目集合V

+0

非常感謝!這正是我想知道的。你的解釋很有意義。 – tristan 2012-07-26 20:48:40

相關問題