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);

    }
}

结果:

posted on 2013-03-08 10:25  Harold H  阅读(7441)  评论(2编辑  收藏  举报

导航