【Java源码分析】String 字符串hashCode

hashCode

hashCode() 方法用于返回字符串的哈希码。

字符串对象的哈希码根据以下公式计算:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

使用 int 算法,这里 s[i] 是字符串的第 i 个字符的 ASCII 码,n 是字符串的长度,^ 表示求幂。空字符串的哈希值为 0。

语法
public int hashCode()
参数
  • 无。
返回值

返回对象的哈希码值。

实例
public class Test {
        public static void main(String args[]) {
                String str = new String("1");
                System.out.println("字符串的哈希码为 :" + str.hashCode() );
        }
}

以上程序执行结果为:49,0的ascii是48

源码
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;
    }

目的,提高比较效率

(1)31是一个不大不小的质数,是作为 hashCode 乘子的优选质数之一

(2)31可以被 JVM 优化,31 * i = (i << 5) - i。

一般在设计哈希算法时,会选择一个特殊的质数。至于为啥选择质数,应该是可以降低哈希算法的冲突率。

猜你喜欢

转载自blog.csdn.net/qq_15604349/article/details/124317404