java string的hashcode

来源:互联网 发布:常用网络用语 日语 编辑:程序博客网 时间:2024/04/25 19:40
Java代码  收藏代码
  1. public int hashCode() {  
  2.     int h = hash;  
  3.     if (h == 0) {  
  4.         int off = offset;  
  5.         char val[] = value;  
  6.         int len = count;  
  7.   
  8.             for (int i = 0; i < len; i++) {  
  9.                 h = 31*h + val[off++];  
  10.             }  
  11.             hash = h;  
  12.         }  
  13.         return h;  
  14.     }  
 

实际上是使用霍纳法则计算h(s)=\sum_{i=0}^{n-1}s[i] \cdot 31^{n-1-i}

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

 

选择31是因为他为素数,且他等于左移5位-1的值,vm会自动做这种优化

 

http://book.douban.com/subject/1610337/  lafore的这本书写的很人性化,没有太多公式,适合入门,第11章讲到了这部分

http://en.wikipedia.org/wiki/Java_hashCode()

http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier

http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html