论坛首页 编程语言技术论坛

Java-HashMap的一点讨论

浏览 1322 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-11-15  

代码如下:

 

public static void main(String[] args)
    {
        Map m = new HashMap();
        Object o1 = new Integer(1);
        Object o2 = new Long(1);
        m.put(o1, 1);
        m.put(o2, 2);
        System.out.println(m.get(1));
        System.out.println(m.get(Long.valueOf(1)));
        System.out.println(o1.hashCode());
        System.out.println(o2.hashCode());
        System.out.println(m.toString());
    }

 

在看我Debug时的图片:

断点处

debug查看内容

好了,想问大家不要去写代码,告诉我程序最后的输出是多少?

答案看附件图片4

 

至于为什么,请看源码:

自己看,我不多说什么,欢迎留言讨论。

 

  • 大小: 8 KB
  • 大小: 12 KB
  • 大小: 2.6 KB
  • 大小: 8.9 KB
  • 大小: 4.4 KB
   发表时间:2012-11-16   最后修改:2012-11-16
楼猪是要考察哪点?

我感觉可能是对hashcode的理解吧。(虽然System.out.println(o2.hashCode());  我确实不记得了,以为和Integer一致)

Integer 是int的包装类,所以hashcode应该==其本身
Long 我原以为同Integer是一样的(虽然这个例子的结果都是1其实不然,楼猪这个例子还不能完全说明问题)Long的hash是把负数 and 0 处理成0,正数和Integer原理一致。

用这个验证既可:
System.out.println(new Long(-1).hashCode());
System.out.println(new Long(1).hashCode());
0 请登录后投票
   发表时间:2012-11-16  
cectsky 写道
楼猪是要考察哪点?

我感觉可能是对hashcode的理解吧。(虽然System.out.println(o2.hashCode());  我确实不记得了,以为和Integer一致)

Integer 是int的包装类,所以hashcode应该==其本身
Long 我原以为同Integer是一样的(虽然这个例子的结果都是1其实不然,楼猪这个例子还不能完全说明问题)Long的hash是把负数 and 0 处理成0,正数和Integer原理一致。

用这个验证既可:
System.out.println(new Long(-1).hashCode());
System.out.println(new Long(1).hashCode());

说明两点:
1. jdk自带的hashmap是用数组链表实现的
2. hashcode值相同只是决定了数组的下标,而key对象才是真正决定map的映射的
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics