String的hashCode可能会返回负数&解决方案
String的hashCode可能会返回负数&解决方案
产生原因:
- 可以查看String hashCode()的源码,会发现,它使用的是int类型,这个时候如果字符串过长,则会溢出
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;
}
解决方案:
- 不能直接使用abs,abs也可能溢出,例如
System.out.println(Math.abs(Integer.MIN_VALUE));
输出的是-2147483648 - 可以使用
str.hashCode()&Integer.MAX_VALUE;
来保证为正数