gpt4 book ai didi

java - 简单的哈希函数技术

转载 作者:行者123 更新时间:2023-12-01 19:35:50 26 4
gpt4 key购买 nike

我对 Java 中的散列还很陌生,并且在某些部分上遇到了困难。我有一个包含 400 个项目的列表(并存储在 1.5x = 600 的列表中),其中项目 id 的范围为 1-10k。我一直在研究一些哈希函数,并且最初复制了数据包中的示例,这些示例仅使用了折叠。我注意到我得到了大约 50-60% 的空节点,这显然太多了。我还注意到,仅将 id 修改 600 往往会将其减少到固定的 50% 空值。

我当前的哈希函数看起来像这样,尽管它很丑陋,但通过简单的修改,它减少了 1% 的空值,平均列表长度为 1.32...

   public int getHash( int id )
{
int hash = id;

hash <<= id % 3;
hash += id << hash % 5;

/* let's go digit by digit! */
int digit;
for( digit = id % 10;
id != 0;
digit = id % 10, id /= 10 )
{
if ( digit == 0 ) /* prevent division by zero */
continue;
hash += digit * 2;
}

hash >>= 5;
return (hash % 600);
}

创建简单哈希函数有哪些好的技术?

最佳答案

我会保持简单。返回元素的 id 作为哈希码,并让哈希表在认为需要时重新哈希它。 您的目标应该是为您的对象创建唯一的哈希码

Java HashMap 使用以下重新哈希方法:

/**
* Applies a supplemental hash function to a given hashCode, which
* defends against poor quality hash functions. This is critical
* because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits. Note: Null keys always map to hash 0, thus index 0.
*/
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);
}

关于java - 简单的哈希函数技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5642881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com