String.hash

/**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@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 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

 String类内部维护一个char[] 别名叫value存储的是String的值,内部维护一个int 别名叫hash存储的是String对象的hash值。String重写hashcode()方法该方法返回的是s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]其中s指的是该对象内部维护的char[] value,n指的是value的长度

猜你喜欢

转载自xiaoxiaoher.iteye.com/blog/2362074
今日推荐