为什么HashMap.put比较哈希和测试相等? [英] Why does HashMap.put both compare hashes and test equality?

查看:115
本文介绍了为什么HashMap.put比较哈希和测试相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java分析 HashMap 源代码,并得到一个关于 put 方法的问题。

I analyse the HashMap source code in Java and get a question about the put method.

以下是JDK1.6中的 put 方法:

Below is the put method in JDK1.6:

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

我对感到困惑如果(e.hash == hash&&((k = e.key)== key || key.equals(k)))

为什么这样的条件?

因为在Java超类 Object 中,有一个合约 hashCode 等于

Because in Java super class Object, there is a contract of hashCode and equals:


如果两个对象相等则到equals(Object)方法,然后在两个对象中的每一个上调用hashCode方法必须产生相同的整数结果。

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

所以 key.equals(k)暗示 key.hashCode()== k.hashCode()

哈希()如下:

 static int hash(int h) {
    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

因此 key.hashCode()== k。 hashCode()暗示 e.hash == hash

为什么isn'条件如 if((k = e.key)== key || key.equals(k))

So why isn't the condition like if ((k = e.key) == key || key.equals(k))?

推荐答案

这只是一个优化:比较两个整数比调用 equals()更快。

It's just an optimization: comparing two integers is faster than calling equals().

如果两个哈希码不同,那么,基于的合约等于 hashCode ,地图知道现有的密钥不等于给定密钥,并且可以更快地到达下一个密钥。

If the two hashcodes differ, then, based on the contract of equals and hashCode, the map knows that the existing key isn't equal to the given key, and can go faster to the next one.

这篇关于为什么HashMap.put比较哈希和测试相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆