欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

String的hashCode分析

程序员文章站 2024-03-22 17:51:04
...
 /**
     * 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.
     */
    private int hash;
    private char[] value;
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; }

  上面是hashCode源码,源码英文翻译就是,调用这个方法返回一个int值。空字符串的hashCode为0。hash值主要用来比较String是否equals,但不一定 ==。

  至于为什么用31去构造算法,从数学上,31质数可以在JVM中很好的分配hashCode,如果数字相乘过大会导致溢出,从而导致数据的丢失。