Java 为什么HashMap.put两者都比较哈希和测试相等性?

Java 为什么HashMap.put两者都比较哈希和测试相等性?,java,hashmap,Java,Hashmap,我分析了Java中的HashMap源代码,得到了一个关于put方法的问题 以下是JDK1.6中的put方法: 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

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

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

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;
}
因此,
key.hashCode()==k.hashCode()
意味着
e.hash==hash


那么为什么条件不是
if((k=e.key)==key | | key.equals(k))

它只是尽可能避免方法调用:如果散列(不是
hashCode()
,它是映射自己的散列)与条目的散列不同,它知道它根本不需要调用
equals
。只是优化一点。

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


如果两个hashCode不同,则根据
equals
hashCode
的约定,映射知道现有键不等于给定键,可以更快地转到下一个键。

hash'变量的值可以与键hashCode不同hash变量是调用hash(key.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);
}