一般hashcode重写都采用了31作为因子
如以下源码
首先31是一个奇数,乘或异或不太重复,分散效果好
其次31有计算优势,31 * i == 32 * i - i == (i << 5) - i.
将乘法转成移位和减法,提高了计算效率。
如以下源码
@Override
public int hashCode() {
if (!dirty) {
return hashCode;
}
int result = Arrays.hashCode(pattern);
result = 31 * result + Longs.hashCode(support);
result = 31 * result + length;
hashCode = result;
return result;
}
首先31是一个奇数,乘或异或不太重复,分散效果好
其次31有计算优势,31 * i == 32 * i - i == (i << 5) - i.
将乘法转成移位和减法,提高了计算效率。