java - 关于hashmap中hashcode的问题
PHP中文网
PHP中文网 2017-04-17 11:23:32
[Java讨论组]

http://blog.sina.com.cn/s/blog_7d17f3cc01014dva.html文章中说道一句话,“在使用自定义对象做key的时候,一定要去实现hashcode方法,不然hashmap就成了纯粹的链表,查找性能非常的慢,添加节点元素也非常的慢”
我非常不理解,主要不理解这个hashcode是怎么算的呢,如果根据对象地址来算的话,也不会出现上面说的问题

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
大家讲道理

很有兴趣讨论一下这个hashcode().

  • java api里的Object.hashcode():

(This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)

看代码可以知道, hashcode()是一个native函数, 但实际JVM会不会直接用对象地址来做hashcode有待探讨, 因为现代的JVM 堆都是分代管理的, 一个Object很可能在一次 GC后改变其对象地址.而对一个对象来说, 其生命周期内的hashcode是不会变的.

  • Effective Java里提到自定义hashcode()的recipe(实际上在Eclipse里, 右键-> Source -> Generate hashcode and Equals可以代劳).大概例子这样:
    private String s;
    private int a;
    private short b;
    private Date d;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + a;
        result = prime * result + b;
        result = prime * result + ((d == null) ? 0 : d.hashCode());
        result = prime * result + ((s == null) ? 0 : s.hashCode());
        return result;
    }

JVM中Object.hashCode()实现

In summary, the notion that Object.hashCode() is based on the object's
address is largely a historic artefact that has been obsoleted by the
properties of modern garbage collectors.

PHP中文网

看文档:http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode() 默认就是用地址。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号