关于String重写的hashcode的代码分析

 1 public int hashCode() {
 2     int h = hash;
 3     if (h == 0 && value.length > 0) {
 4         char val[] = value;
 5 
 6         for (int i = 0; i < value.length; i++) {
 7             h = 31 * h + val[i];
 8         }
 9         hash = h;
10     }
11     return h;
12 }

可以发现其仅是根据字符内容采用加权求和的方法得到hashcode

特殊的是其选择的质数31,31有什么特殊的含义呢?

经查阅相关资料:

  • 31可以被 JVM 优化,31 * i = (i << 5) - i
  • 降低哈希算法得冲突率

关于第二点,由于int仅32位,而字符串是无限的,所以必定会出现冲突,但是通过更均匀的分散哈希值能够降低两个字符串对同一hashcode mod2^31表示的的争夺。

而为什么31更好可以查看相关数学证明,也可以直接枚举验证。

原文地址:https://www.cnblogs.com/gjl-blog/p/8502704.html