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 ;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM