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

    }
}

结果:

转载于:https://www.cnblogs.com/harold125/archive/2013/03/08/2949389.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值