Java中String的hash函數分析

來源:互聯網
上載者:User

JDK6的源碼:

    /**     * Returns a hash code for this string. The hash code for a     * <code>String</code> object is computed as     * <blockquote><pre>     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]     * </pre></blockquote>     * using <code>int</code> arithmetic, where <code>s[i]</code> is the     * <i>i</i>th character of the string, <code>n</code> is the length of     * the string, and <code>^</code> indicates exponentiation.     * (The hash value of the empty string is zero.)     *     * @return  a hash code value for this object.     */    public int hashCode() {int h = hash;if (h == 0) {    int off = offset;    char val[] = value;    int len = count;            for (int i = 0; i < len; i++) {                h = 31*h + val[off++];            }            hash = h;        }        return h;    }

以字串"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值的:

public class Name{String firstName;String lastName;@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result+ ((firstName == null) ? 0 : firstName.hashCode());result = prime * result+ ((lastName == null) ? 0 : lastName.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Name other = (Name) obj;if (firstName == null) {if (other.firstName != null)return false;} else if (!firstName.equals(other.firstName))return false;if (lastName == null) {if (other.lastName != null)return false;} else if (!lastName.equals(other.lastName))return false;return true;}}

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

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

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

總結:字串hash函數,不僅要減少衝突,而且要注意相同首碼的字串產生的hash值要相鄰。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.