2017-08-09 99 views
1
HashMap<Integer,List<Integer>> test = new HashMap<Integer,ArrayList<Integer>>(); 

此行給我的錯誤:HashMap<Integer,ArrayList<Integer>> cannot be converted to HashMap<Integer,List<Integer>>爲什麼不能HashMap的<整數,ArrayList的<Integer>>轉換爲HashMap的<整數,列表<Integer>>

我不明白爲什麼這不起作用。

+2

您使用的是Java 7+嗎?使用菱形運算符.. .'Map = new HashMap <>()' –

+0

嗯我不知道版本,因爲我使用Leetcode的在線Java環境。 – varimax

+0

我懷疑它卡在Java 6中 –

回答

2

相關HashMap將被限制爲ArrayList s,但該參考將允許您添加任何類型的列表。如果您嘗試將LinkedList添加到HashMap,該怎麼辦?

也許,你只需要做出HashMapList的:

HashMap<Integer, List<Integer>> test = new HashMap<Integer, List<Integer>>(); 

或者,如果你真的想,它僅包含ArrayList S上的限制:

HashMap<Integer, ArrayList<Integer>> test = new HashMap<Integer, ArrayList<Integer>>(); 

注意,這種問題被稱爲協變和逆變。

另請參見:

此鏈接是有關C#不是Java的,但我知道這個概念的最佳解釋之一。它不會以同樣的方式到Java,因爲它確實給C#應用,但它應該是還是一個有用的閱讀:

0

它不工作,因爲它是「不安全」,它是不安全的原因是因爲你將舉行兩場參照同一列表與此兩種類型:

HashMap<Integer,List<Integer>> a; 
HashMap<Integer,ArrayList<Integer>> b; 

因此,如果您現在與未來的價值類型LinkedList<Integer>這將是確定添加的兩項a但它因爲LinkedList不是ArrayList,因此將其添加到b是不行的。因此,通過創建b中的a參考,您將創建一個後門,以從b參考視角來破壞地圖的內容。

例如,某人從b提取值ArrayList將會得到一個LinkedList而不是導致鑄造異常。

相關問題