【发布时间】:2013-04-14 17:18:09
【问题描述】:
我有一个家庭作业,我必须为字典创建一个哈希表,用户可以在其中输入一个单词作为键,它将搜索并显示含义。
但是我不确定从 String 键到 int 键的转换是如何工作的。这是我从教科书中获取的代码:
public int hashVal(String key, int tableSize)
{
int hashKey= 0;
int temp = 0;
for(int i=0;i<key.length();i++)
{
temp = 37*temp+(int)key.charAt(i);
}
temp%=tableSize;
if (temp<0)
{
temp+=tableSize;
}
hashKey=temp;
return hashKey;
}
非常感谢您提供解释或更简单的代码。
【问题讨论】:
-
这会计算你的字符串的哈希值。
temp计算是不必要的,因为string.hashCode()会这样做(除非你也需要实现它)。 mod 操作将 hashCode 减少为哈希索引。整数可以溢出到负数,因此也可以处理。