简体   繁体   English

Java hashmap方法.put()

[英]Java hashmap method .put()

The source code of java.util.HashMap#put(Object, Object) is java.util.HashMap#put(Object, Object)的源代码是

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;
}

I think that if the keys can get the same index in the table(example:key1 and key2 are all in the table[x]), the e.hash == hash will always return true. 我认为,如果键可以在表中获得相同的索引(示例:key1和key2都在表[x​​]中),则e.hash == hash将始终返回true。 Is the code e.hash == hash neccessary for .put() method? .put()方法是否需要代码e.hash == hash

The only one explanation is that the different key.hashCode() after the operate of the hash() and indexFor() method, the result will be may the same, so the code will be necessary. 唯一的解释是,在hash()indexFor()方法操作之后,不同的key.hashCode()的结果可能是相同的,因此代码是必需的。

Is my answer right? 我的答案正确吗? Who can tell me, if e.hash == hash is necessary? 谁能告诉我,是否有必要使用e.hash == hash

e.hash == hash is just an optimization; e.hash == hash只是一种优化; it's not strictly necessary. 这不是绝对必要的。 You're already comparing elements in the same hash bucket, and if two elements are .equals , then they match. 您已经在比较同一哈希存储桶中的元素,并且如果两个元素是.equals ,则它们匹配。 The only point is minimizing expensive .equals checks on elements whose hashes are the same mod the hash table size. 唯一的要点是将散列与散列表大小相同的元素的昂贵的.equals检查最小化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM