我的任务是使用该定义在java中实现字符串的哈希代码。这是我写的代码。
public int hash(String str) {
int hashValue = 0;
int power;
for (int i = 0; i < str.length(); i++) {
power = (str.length() -1 - i);
hashValue = hashValue + str.charAt(i) * (int) Math.pow(31, power);
}
return hashValue;
}我发现,在我的方法中,只有长度小于8的字符串的结果与hashcode()相同。这应该是这样吗?还是我的方法不准确?我已经看到,对于超过8个字符的字符串,哈希代码可能已经发生了变化。
发布于 2018-05-09 20:46:50
查看jdk中的hashCode实现:
public static int hashCode(byte[] value) {
int h = 0;
int length = value.length >> 1;
for (int i = 0; i < length; i++) {
h = 31 * h + getChar(value, i);
}
return h;
}可能发生的情况是,您的方法产生与此相同的结果。事实上,这并不重要。这只是一种散列方法。
注意,散列方法不需要“精确”。它是将任意对象(字符串)还原为int的一种方法。你可以使用任何你想要的方法。
https://stackoverflow.com/questions/50261724
复制相似问题