從String源碼揭秘hashcode()演算法__演算法

來源:互聯網
上載者:User

先看下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

所以計算正確。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.