HashMap的put方法注意


HashMap,在使用put的時候,如果添加的是對象的話,所存儲的都是對象的引用(地址)。從下面的例子中可以看到:

import java.util.HashMap;
import java.util.Map;

public class  MapPut
{
    public static void main(String[] args) 
    {
        Map<Integer,Map<Integer,Integer>> testMap = new HashMap<Integer, Map<Integer,Integer>>();
        
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        map.put(4, 1);
        testMap.put(1663, map);
        testMap.put(1664, map);
        System.out.println(testMap);
        //試圖給1663追加(2,1)
        testMap.get(1663).put(2, 1);

        System.out.println(testMap);

    }
}

輸出的結果如下:

在結果中可以看到,給1663追加的(2,1)同時也會在1664中出現,原因是put(2,1)的操作,通過地址找到堆內存中的map,並且對其進行追加。如此,1664所對應的也是map的引用,所以1664也會看到追加后的結果。

解決的個問題的一種方法是對map進行重新的實例化。

import java.util.HashMap;
import java.util.Map;

class  MapPut
{
    public static void main(String[] args) 
    {
        Map<Integer,Map<Integer,Integer>> testMap = new HashMap<Integer, Map<Integer,Integer>>();
        
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        map.put(4, 1);
        testMap.put(1663, map);

        map = new HashMap<Integer, Integer>();
        map.put(4, 1);
        testMap.put(1664, map);

        System.out.println(testMap);
        //試圖給1663追加(2,1)
        testMap.get(1663).put(2, 1);

        System.out.println(testMap);

    }
}

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM