Java - 对Hashcode的理解

hashcode方法的注释

从下面的注释中可以得出以下几点重要信息:

  • 如果两个对象通过equals方法比较返回true, 那么这两个对象的hashcode()方法返回值也必须一样.
  • 如果用于equals中比较的信息在运行时没有被改变, 那么该对象的hashcode()方法在每次被调用时的返回值应该是相同的.
  • hashcode()返回的hashcode不一定要每次都一致 (比如说用于equals方法中的信息在运行时发生了变化, 那么hashcode应该也会做出相应的变化)
  • 不要求两个equals不等的对象, hashcode也要不同. 即允许两个不equals的对象, 有相同的hashcode. 不过, 如果equals不同的对象, hashcode也不同的话, 可能提高hash table (这里应该是泛指使用了哈希的数据结构) 的性能. (本文后面会讲为什么可能提高性能).
    /**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code equals} comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code hashCode} method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (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&trade; programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

实例

equals()比较相同, 但是hashcode()不同的两个对象, 对于使用hashcode的集合类来说, 会造成什么问题呢?

首先我们实现这么一个类, equals比较相等, 但是hashcode不同.
注意java7以后, 可以使用Objects.hash()方法来计算哈希值.

Objects.hash()方法如下:

    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }

我们的不符合规范的类:

    public static class HashcodeNotCorrespondingToEquals{

        private int id;
        private String name;

        public HashcodeNotCorrespondingToEquals(int id, String name){
            this.id = id;
            this.name = name;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) return false;
            if (!(obj instanceof HashcodeNotCorrespondingToEquals)) return false;

            return name.equals(((HashcodeNotCorrespondingToEquals) obj).name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

测试:

    public static void testHashCodeBug(){
        Set<HashcodeNotCorrespondingToEquals> set = new HashSet<>();
        HashcodeNotCorrespondingToEquals bad1 = new HashcodeNotCorrespondingToEquals(1, "wrong");
        HashcodeNotCorrespondingToEquals bad2 = new HashcodeNotCorrespondingToEquals(2, "wrong");
        HashcodeNotCorrespondingToEquals bad3 = new HashcodeNotCorrespondingToEquals(1, "test");

        boolean equals = bad1.equals(bad2);
        // true
        System.out.println(String.format("%s: %s", "bad1.equals(bad2)", equals));
        set.add(bad1);
        // false
        System.out.println(String.format("set.contains(bad2): %s", set.contains(bad2)));
        // false
        System.out.println(String.format("set.contains(bad3): %s", set.contains(bad3)));
        
    }

输出:

bad1.equals(bad2): true
set.contains(bad2): false
set.contains(bad3): false

逻辑上来说bad1bad2应该是相同的东西, 对于set来说应该只能存在其中一个, 但是从第二条输出可以看出set并没有认为两者相等.

究其原因, 是因为HashSet利用了HashMap实现其功能. 可以看到HashSetadd方法如下:

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

其中map就是一个HashMap实例, 而PRESENT

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

为何两个keyequals的, 但是还是能将两个key都加进去呢? 我们来看看HashMapput方法如何实现:

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

put方法调用了putVal方法, 这里直接给出putVal方法.

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

我们主要看以下一部分:

if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
        // .....省略.....

可以看到HashMap是用hashcode来找到对应的tab下标, 即通过对hashcode的处理, 可以找到一个tab的下标, 而tab[(n-1) & hash]即是用来存放某一类hash值的key的, 这里也体现了对不同对象相同hash值的冲突的处理.

正是因为找tab下标这个过程仅使用了hash值, 所以如果keyequals的, 但是hashcode不同, 那么得到的tab下标也很有可能是不同的, 所以可能会导致在tab链中找不到以前加入的和当前key本质上相等的key, 导致set的行为被破坏.

注意这条if判断,

if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))

从这里可以看出为什么如果实现了equals不同, hashcode也不同的话, 可能会提高hash结构的效率. HashMap检查这个key是否存在, 会依据hashcode来找下标, 然后在对应下标的tab链中, 寻找可能和现在要加的key相等的key.

如果之前加入的某个keyp.hash(p用于遍历现存的key)和当前想要加入的keyhash是不同的, 那么根据短路求值, 后面&&部分根本不会计算了, 所以效率会更高.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 4,243评论 0 16
  • 前言 今天来介绍下HashMap,之前的List,讲了ArrayList、LinkedList,就前两者而言,反映...
    嘟爷MD阅读 2,864评论 2 56
  • HashMap 是 Java 面试必考的知识点,面试官从这个小知识点就可以了解我们对 Java 基础的掌握程度。网...
    野狗子嗷嗷嗷阅读 6,636评论 9 107
  • 朱的事情自己处理的有点操之过急了。分寝室之前,我了解了一下她们寝室的情况,她算是比较爱说话的,所以分寝室的时候,我...
    蜗牛100阅读 216评论 0 0
  • “咕咕、咕咕”“磨镰、割麦”清晨醒来,远处传来布谷鸟清脆的叫声,记得小时候母亲说这是布谷鸟在催着人们麦收呢。随着我...
    云端儿阅读 333评论 0 1