2013-10-06 48 views
1

我有一個HashMap實現爲:錯誤而遍歷一個ArrayList內的HashMap

Map<Integer, ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>(); 

以下操作後:

hm.put((Integer) 1, new ArrayList<Integer>()); 
hm.put((Integer) 2, new ArrayList<Integer>()); 
(hm.get(1)).add(2); 
(hm.get(1)).add(2); 
(hm.get(1)).add(3); 
(hm.get(2)).add(4); 

我得到我的地圖爲:

1: [2,2,3] 
2: [4] 

現在,我想從鍵1中刪除所有2的出現,即,我想修改我的HashMap,使其看起來像:

1: [3] 
2: [4] 

我做了以下內容:

for(List<Integer> list : (hm.get(1))) 
{ 
    list.removeAll(Collections.singleton(2)); 
} 

然而,儘管編譯,這個錯誤顯示出來:

error: incompatible types 
     for(List<Integer> list : hm.get(1)) 
            ^
required: List<Integer> 
found: Integer 
1 error 

然而,當我運行:

System.out.println((hm.get(1)).getClass()); 

我得到:

class java.util.ArrayList 

根據我想這,我的代碼是罰款(即使在應用石膏後,這種錯誤的另一種形式顯示出來)。

我不知道爲什麼會發生這種情況。我究竟做錯了什麼?如何解決這個問題?

回答

5

變量的類型在for-each循環應存儲在收藏你遍歷元素的類型協變的。

hm.get(1)會讓你的List<Integer>映射到密鑰1。迭代List<Integer>會得到一個Integer,而你試圖將它存儲在List<Integer>for-each變量應該是Integer而不是List<Integer>。更好的是int,因爲Integer反正會被拆箱到int

話雖如此,根本不需要那個循環。只是下面的代碼將工作:

hm.get(1).removeAll(Collections.singleton(2)); 

此外,還有一些其他重要的問題在您的代碼。例如:

  1. 你現在的樣子做put()

    hm.put((Integer) 1, new ArrayList<Integer>()); 
    

    更好寫成:

    hm.put(1, new ArrayList<Integer>()); 
    

    1將自動裝箱爲Integer包裝。你不必擔心這一點。

  2. 另外,在鏈接方法調用時,不需要用括號括起每個方法調用。所以,

    (hm.get(1)).add(2); 
    

    是更好的寫法如下:

    hm.get(1).add(2); 
    
  3. 第三,這是更好地申報自己的地圖爲:

    Map<Integer, List<Integer>> hm = new HashMap<Integer, List<Integer>>(); 
    

    它只是爲您提供添加LinkedList或靈活性一個ArrayList或地圖內的任何其他實現。

+0

非常感謝。我是編程新手,你的投入肯定教會了我一些東西。 –

+0

@TarunVerma不客氣:) –

3

您正試圖遍歷您的List<Integer>,而不是直接使用它。跳過for循環,只是做

hm.get(1).removeAll(Collections.singleton(2));