2014-04-05 15 views
0

假設我有接口(或超類,無所謂)Program和實現Firefox。我想在某些類中定義一個映射爲Map<Long,Program> mapOfPrograms,然後通過依賴注入在setter集mapOfPrograms = new TreeMap<Long,Firefox>();中。我需要能夠做到mapOfPrograms.put(1l,new Firefox());mapOfPrograms.put(1l,(Program)(new Firefox()));然後我需要能夠get並使用這些對象。我收到錯誤Type Mismatch: cannot convert from Map<Long,Program> to TreeMap<Long,Firefox>。如果Program是接口或超類,則無關緊要。如何獲取java中的接口或超類的地圖

我該如何解決這個問題?

+0

閱讀有關[佩奇(http://stackoverflow.com/questions/2723397/java-generics-what-is -pecs)。 –

回答

1

試試這個

class MyMap<K,T extends Program> extends TreeMap<K,Program>{ 

    private static final long serialVersionUID = 1L; 

} 

interface Program{ 

} 

class Firefox implements Program{ 

} 

這裏是你的代碼

Map<Long, Program> map=new MyMap<Long,Firefox>(); 
    map.put(1L, new Firefox()); 
+0

由於'MyMap'已被參數化,您可以定義「Long」以外的其他鍵。 – Braj

+0

+1,這個解決方案能讓我像普通人一樣得到嗎?爲什麼我不使用'?超級? – user2763361

+0

請讓我檢查。 – Braj

相關問題