JDK中String的hashCode方法的实现方法如下:
1
public
int
hashCode() {
2 int h = hash;
3 int len = count;
4 if (h == 0 && len > 0 ) {
5 int off = offset;
6 char val[] = value;
7
8 for ( int i = 0 ; i < len; i ++ ) {
9 h = 31 * h + val[off ++ ];
10 }
11 hash = h;
12 }
13 return h;
14 }
2 int h = hash;
3 int len = count;
4 if (h == 0 && len > 0 ) {
5 int off = offset;
6 char val[] = value;
7
8 for ( int i = 0 ; i < len; i ++ ) {
9 h = 31 * h + val[off ++ ];
10 }
11 hash = h;
12 }
13 return h;
14 }
对于为什么选取31而不是32作为基数,下面两个链接中的讨论解释了这个问题,概括起来就是使用31可以有效的减少冲突,32会使不同字符串取得相同hashCode的概率大幅增加。