截自String类中hashCode计算方法的源码,其中hash的初始值为0,value的值为字符串对应的字符数组。


上面代码不难理解,
对于空字符串,长度为0,不进入if条件,返回初始值0。
对于非空字符串,将每个字符走一遍上面的for循环就是答案了,for循环中的h = 31 * h + val[i];val[ i ]值为字符对应的unicode编码。
关于unicode编码:https://blog.csdn.net/atwdy/article/details/124714440
验证一下
对于字符串"abc",对应的unicode编码:a: 97,b: 98,c: 99
h = 31 x 0 + 97 = 97
h = 31 x 97 + 98 = 3105
h = 31 x 3105 + 99 = 96354
对于包含汉字的字符串"飞鱼a",对应的unicode编码:飞: 39134,鱼: 40060,a: 97
h = 31 x 0 + 39134 = 39134
h = 31 x 39134 + 40060 = 1253214
h = 31 x 1253214 + 97 = 38849731
public class Demo {
public static void main(String[] args) {
System.out.println("abc".hashCode());
System.out.println("飞鱼a".hashCode());
}
}
