java IdentityHashMap 与HashMap

来源:互联网 发布:淘宝网买车 编辑:程序博客网 时间:2024/04/29 16:53
这两个map的主要区别在于比较key值的时候:
IdentityHashMap认为当k1 == k2 时key值是一样的
HaspMap认为k1 == null ? k2 == null:k1.equals(k2)时key值是一样的

举个例子:
Integer a = new Integer(123456);
           Integer b = new Integer(123456);
           HashMap hashMap = new HashMap();
           IdentityHashMap identityHashMap = new IdentityHashMap();
           hashMap.put(a,1);
           hashMap.put(b, 2);
           identityHashMap.put(a,1);
           identityHashMap.put(b,2);
           System.out.println(hashMap);
           System.out.println(identityHashMap);

运行结果:
P_LOG: {123456=2}
P_LOG: {123456=1, 123456=2}

总结:
          HashMap:会使用equals比较key对象
          IdentityHashMap:使用 == 比较key对象
      



0 0