我有一個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
根據我想這,我的代碼是罰款(即使在應用石膏後,這種錯誤的另一種形式顯示出來)。
我不知道爲什麼會發生這種情況。我究竟做錯了什麼?如何解決這個問題?
非常感謝。我是編程新手,你的投入肯定教會了我一些東西。 –
@TarunVerma不客氣:) –