java - 证明 : why does java. lang.String.hashCode() 的实现与其文档相匹配?

标签 java algorithm math hashcode

java.lang.String.hashCode() 的 JDK 文档famously说:

The hash code for a String object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the *i*th character of the string, n is the length of the string, and ^ indicates exponentiation.

这个表达式的标准实现是:

int hash = 0;
for (int i = 0; i < length; i++)
{
    hash = 31*hash + value[i];
}
return hash;

看着这个让我觉得我正在通过我的算法类(class) sleep 。该数学表达式如何转化为上面的代码?

最佳答案

展开循环。然后你得到:

int hash = 0;

hash = 31*hash + value[0];
hash = 31*hash + value[1];
hash = 31*hash + value[2];
hash = 31*hash + value[3];
...
return hash;

现在您可以进行一些数学运算,为初始哈希值插入 0:

hash = 31*(31*(31*(31*0 + value[0]) + value[1]) + value[2]) + value[3])...

再简化一下:

hash = 31^3*value[0] + 31^2*value[1] + 31^1*value[2] + 31^0*value[3]...

这基本上就是给定的原始算法。

关于java - 证明 : why does java. lang.String.hashCode() 的实现与其文档相匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/822363/

相关文章:

python - python负数的立方根

math - 破译 amsco 密码

java - 通过 TCP 接收用户定义的对象并出现 ClassNotFoundException

java - JDBC 回滚方法的行为与预期不同

algorithm - 按相似度进行人脸聚类

php - 下料问题

javascript - 寻找一种算法来聚类 3d 点,围绕 2d 点

java - 如何更新名称相同的 session.setAttribute(name,value) 值?

java - 扩展堆栈库

c# - 任务在一天中占用的小时数的算法