简体   繁体   English

为什么HashTable在java中存储表中键的哈希值

[英]Why does a HashTable store the hash value of the key in the table in java

I was going through Java's implementation of the put method for a hashtable and came across this : 我正在通过Java的hash方法实现put方法,并遇到了这个:

// Makes sure the key is not already in the hashtable.
    Entry tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
        if ((e.hash == hash) && e.key.equals(key)) {
            V old = e.value;
            e.value = value;
            return old;
        }
    }

While I understand that a key is required to check for collisions, why is Java storing the hash value of the key and also checking it ? 虽然我知道需要一个密钥来检查冲突,但为什么Java存储密钥的哈希值并检查它?

Because the same bucket ( tab ) can hold items having different hashes due to % tab.length operation. 因为% tab.length操作,相同的桶( tab )可以保存具有不同散列的项目。 Checking hash first is probably some performance optimization to avoid calling equals() if hashes are different. 首先检查哈希可能是一些性能优化,以避免在哈希值不同时调用equals()

To put this in an example: Say you have two complex objects with costly equals() method. 举一个这样的例子:假设你有两个带有昂贵的equals()方法的复杂对象。 One object has hash equal to 1 while the other object has hash of 32. If you put both objects in a hash table having 31 buckets, they'll end up in the same bucket ( tab ). 一个对象具有等于1的散列,而另一个对象具有32的散列。如果将两个对象放在具有31个桶的散列表中,它们将最终位于同一个桶( tab )中。 When adding a second (different object) you must make sure it's not yet in the table. 添加第二个(不同的对象)时,必须确保它还没有在表中。 You can use equals() immediately, but this might be slower. 您可以立即使用equals() ,但这可能会更慢。 Instead you first compare hashes, avoiding costly equals() if not necessary. 相反,你首先比较哈希,如果没有必要,避免代价高昂的equals() In this example hashes are different (despite being in the same bucket) so equals() is not necessary. 在这个例子中,哈希是不同的(尽管在同一个桶中)所以equals()不是必需的。

It makes access faster, since the hash value does not need to be recomputed for every access. 它使访问速度更快,因为不需要为每次访问重新计算哈希值。 This is important not just for explicit searches (where the hash is checked before doing equals ) but also for rehash. 这不仅对显式搜索(在执行equals之前检查哈希)以及rehash非常重要。

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

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