zoukankan      html  css  js  c++  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 ;

  • 相关阅读:
    vss的ss.ini丢失或损坏导致的vss无法登录错误
    NHibernate各种数据库连接参数文件配置方法说明
    oracle操作语句
    企业微信群聊机器人发送本地图片
    securecrt 或xshell 转发80端口
    SecureCRT 或 XSHELL 转发 X11 图形化GUI
    Windows 创建 .gdbinit 提示必须键入文件名
    vscode C++ 程序 windows
    vscode C++ 程序 windows
    解决source insight 4.0 不识别.cc文件的问题
  • 原文地址:https://www.cnblogs.com/yaowen/p/8609470.html
Copyright © 2011-2022 走看看