本文介绍了证明:为什么java.lang.String.hash code()的实现匹配它的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JDK文档中的 著名说:

标准执行这一前pression是:

  INT哈希= 0;
的for(int i = 0; I<长度;我++)
{
    哈希= 31 *哈希值+ [I]
}
返回哈希;
 

看着这让我觉得我是通过我的算法当然睡觉。这是如何数学EX pression转化为code以上?

解决方案

我不知道,如果你错过了它说:^表示幂(而不是XOR)的文档。

通过每一次循环,哈希的previous值31的再次的被添加到下一个元素之前值。

一个可以证明这些东西都是平等的感应,但我觉得一个例子可能更明确的:

说我们正在处理4字符的字符串。让我们展开循环:

 散= 0;
哈希= 31 *哈希值+ [0];
散列= 31 * +散列值[1];
哈希= 31 *哈希值+ [2];
散列= 31 * +散列值[3];
 

现在,这些通过哈希各值代入下面的语句合并为一个语句:

 散= 31 *(31 *(31 *(31 * 0 +值[0])+值[1])+值[2])
     值+ [3];
 

31 * 0是0,因此简化:

 散= 31 *(31 *(31 *值[0] +值[1])+值[2])
     值+ [3];
 

现在由第二个31相乘的两个内项

 散= 31 *(31 * 31 *值[0] + 31 *值[1] +值[2])
     值+ [3];
 

现在由第31乘以三个内条款

 散= 31 * 31 * 31 *值[0] + 31 * 31 *值[1] + 31 *值[2]
     值+ [3];
 

和转换成指数(不是真正的Java了):

 散= 31 ^ 3 *值[0] + 31 ^ 2 *值[1] + 31 ^ 1 *值[2] +值[3]。
 

The JDK documentation for java.lang.String.hashCode() famously says:

The standard implementation of this expression is:

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

Looking at this makes me feel like I was sleeping through my algorithms course. How does that mathematical expression translate into the code above?

解决方案

I'm not sure if you missed where it says "^ indicates exponentiation" (not xor) in that documentation.

Each time through the loop, the previous value of hash is multipled by 31 again before being added to the next element of value.

One could prove these things are equal by induction, but I think an example might be moreclear:

Say we're dealing with a 4-char string. Let's unroll the loop:

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

Now combine these into one statement by substituting each value of hash into the following statement:

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

31 * 0 is 0, so simplify:

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

Now multiply the two inner terms by that second 31:

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

Now multiply the three inner terms by that first 31:

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

and convert to exponents (not really Java anymore):

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

这篇关于证明:为什么java.lang.String.hash code()的实现匹配它的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 14:00