簡體   English   中英

在HashMap中遍歷ArrayList時出錯

[英]Error while iterating over an ArrayList inside HashMap

我有一個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

據此,我認為我的代碼很好(即使在應用強制轉換后,此錯誤也以另一種形式出現)。

我不知道為什么會這樣。 我究竟做錯了什么? 如何解決這個問題?

for-each循環中的變量類型應與要迭代的Collection中存儲的元素的類型協變。

hm.get(1)將為您提供映射到鍵1List<Integer> 在該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>>(); 

    它只是為您提供了在地圖內添加LinkedListArrayList或任何其他實現的靈活性。

您嘗試遍歷List<Integer>而不是直接使用它。 跳過for循環,然后執行

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM