Java中String的hash函數分析


轉載自:http://blog.csdn.net/hengyunabc/article/details/7198533


JDK6的源碼:

[java]  view plain copy
  1.    /** 
  2.     * Returns a hash code for this string. The hash code for a 
  3.     * <code>String</code> object is computed as 
  4.     * <blockquote><pre> 
  5.     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 
  6.     * </pre></blockquote> 
  7.     * using <code>int</code> arithmetic, where <code>s[i]</code> is the 
  8.     * <i>i</i>th character of the string, <code>n</code> is the length of 
  9.     * the string, and <code>^</code> indicates exponentiation. 
  10.     * (The hash value of the empty string is zero.) 
  11.     * 
  12.     * @return  a hash code value for this object. 
  13.     */  
  14.    public int hashCode() {  
  15. int h = hash;  
  16. if (h == 0) {  
  17.     int off = offset;  
  18.     char val[] = value;  
  19.     int len = count;  
  20.   
  21.            for (int i = 0; i < len; i++) {  
  22.                h = 31*h + val[off++];  
  23.            }  
  24.            hash = h;  
  25.        }  
  26.        return h;  
  27.    }  


以字符串"123"為例:

字符'1'的ascii碼是49

hashCode = (49*31 + 50)*31 + 51

或者這樣看:

hashCode=('1' * 31 + '2' ) * 31 + '3'

可見實際可以看作是一種權重的算法,在前面的字符的權重大。

這樣有個明顯的好處,就是前綴相同的字符串的hash值都落在鄰近的區間。

好處有兩點:

1.可以節省內存,因為hash值在相鄰,這樣hash的數組可以比較小。比如當用HashMap,以String為key時。

2.hash值相鄰,如果存放在容器,比好HashSet,HashMap中時,實際存放的內存的位置也相鄰,則存取的效率也高。(程序局部性原理)


以31為倍數,原因了31的二進制全是1,則可以有效地離散數據。

最后看下,兩個字符串,由Eclipse生成的代碼是如何計算hash值的:

[java]  view plain copy
  1. public class Name{  
  2.     String firstName;  
  3.     String lastName;  
  4.     @Override  
  5.     public int hashCode() {  
  6.         final int prime = 31;  
  7.         int result = 1;  
  8.         result = prime * result  
  9.                 + ((firstName == null) ? 0 : firstName.hashCode());  
  10.         result = prime * result  
  11.                 + ((lastName == null) ? 0 : lastName.hashCode());  
  12.         return result;  
  13.     }  
  14.   
  15.     @Override  
  16.     public boolean equals(Object obj) {  
  17.         if (this == obj)  
  18.             return true;  
  19.         if (obj == null)  
  20.             return false;  
  21.         if (getClass() != obj.getClass())  
  22.             return false;  
  23.         Name other = (Name) obj;  
  24.         if (firstName == null) {  
  25.             if (other.firstName != null)  
  26.                 return false;  
  27.         } else if (!firstName.equals(other.firstName))  
  28.             return false;  
  29.         if (lastName == null) {  
  30.             if (other.lastName != null)  
  31.                 return false;  
  32.         } else if (!lastName.equals(other.lastName))  
  33.             return false;  
  34.         return true;  
  35.     }     
  36. }  

可見,還是以31為倍數, hashCode = firstName.hashCode() * 31 + lastName.hashCode() 。

BTW:Java的字符串的hash做了緩存,第一次才會真正算,以后都是取緩存值。

eclipse生成的equals函數質量也很高,各種情況都考慮到了。


總結:字符串hash函數,不僅要減少沖突,而且要注意相同前綴的字符串生成的hash值要相鄰。



免責聲明!

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



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