String类的hashcode计算

来源:互联网 发布:mac spine1.7.03 安装 编辑:程序博客网 时间:2024/06/14 16:12
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;}

源码如上。
关于为什么取31为权

主要是因为31是一个奇质数,所以31*i=32*i-i=(i<<5)-i,这种位移与减法结合的计算相比一般的运算快很多。

比如:

String ss = "abc";String ss1 = new String("abc");String ss2 = "abc";System.out.println(ss.equals(ss1));//trueSystem.out.println(ss.equals(ss2));//trueSystem.out.println(ss == ss1);//false

hashcode值一样,对象不一定一样
对象一样,hashcode值一样