String源码中hashCode算法

Java String hashCode详解
本文深入解析了Java中String类的hashCode方法实现原理,通过具体的源码分析和实例演示,详细解释了如何根据字符串内容计算其哈希值的过程。

针对java中String源码hashcode算法源码分析

 

Java代码  收藏代码
  1. /** The value is used for character storage. */  
  2. private final char value[];  //将字符串截成的字符数组  
  3.   
  4. /** Cache the hash code for the string */  
  5. private int hash; // Default to 0 用以缓存计算出的hashcode值  
  6.   
  7. /** 
  8.   * Returns a hash code for this string. The hash code for a 
  9.   * <code>String</code> object is computed as 
  10.   * <blockquote><pre> 
  11.   * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 
  12.   * </pre></blockquote> 
  13.   * using <code>int</code> arithmetic, where <code>s[i]</code> is the 
  14.   * <i>i</i>th character of the string, <code>n</code> is the length of 
  15.   * the string, and <code>^</code> indicates exponentiation. 
  16.   * (The hash value of the empty string is zero.) 
  17.   * 
  18.   * @return  a hash code value for this object. 
  19.   */  
  20.   public int hashCode() {  
  21.         int h = hash;  
  22.         if (h == 0 && value.length > 0) {  
  23.             char val[] = value;  
  24.   
  25.             for (int i = 0; i < value.length; i++) {  
  26.                 h = 31 * h + val[i];  
  27.             }  
  28.             hash = h;  
  29.         }  
  30.         return h;  
  31.     }  

 按照上面源码举例说明:

 

String msg = "abcd";  // 此时value[] = {'a','b','c','d'}  因此

for循环会执行4次

第一次:h = 31*0 + a = 97 

第二次:h = 31*97 + b = 3105 

第三次:h = 31*3105 + c = 96354 

第四次:h = 31*96354 + d = 2987074 

由以上代码计算可以算出 msg 的hashcode = 2987074  刚好与 System.err.println(new String("abcd").hashCode()); 进行验证

 

在源码的hashcode的注释中还提供了一个多项式计算方式:

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

s[0] :表示字符串中指定下标的字符

n:表示字符串中字符长度

a*31^3 + b*31^2 + c*31^1 + d = 2987074  + 94178 + 3069 + 100 = 2987074 ;

转载于:https://www.cnblogs.com/yaowen/p/8609470.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值