先看下java源碼中對hashcode()方法裡面用到的變數的聲明。
/** The value is used for character storage. */ private final char value[];//定義一個字元數組value,用於儲存字串裡面的字元 /** The offset is the first index of the storage that is used. */ private final int offset;//定義offset變數表示字串第一個字元的下標索引 /** The count is the number of characters in the String. */ private final int count;//定義count變數表示字串中字元的個數 /** Cache the hash code for the string */ private int hash; // Default to 0,預設值為0
下面就是hashcode()方法的源碼
/** * 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 && count > 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; }
下面以cat為例。根據hashcode()源碼中的迴圈部分的演算法,計算一下cat的hashcode值
首先,c,a,t 的ascii碼值分別為99,97,116;字元個數3,所以迴圈部分的代碼變成如下所示
public int hashCode() { int h = hash; if (h == 0 && count > 0) { int off = 0; char val[] = value; int len = 3; for (int i = 0; i < 3; i++) { h = 31*h + val[off++]; } hash = h; } return h; }
也就是總共3次迴圈
第一次迴圈:h1=31*0+val[0]=val[0]='c'=99
第二次迴圈:h2=31*h1+val[1]=31*99+'a'=31*99+97=3166
第三次迴圈:h3=31*h2+val[2]=31*3166+'t'=31*3166+116=98262
所以cat的hashcode值為98262
再用多項式的表示方法檢驗一下s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
99*31的平方+97*31+116結果也等於98262
所以計算正確。