java String hashCode遇到的坑

在进行数据交换时,如果主键不是整型,需要对字符串,或联合主键拼接为字符串,进行hash,再进行取模分片,使用的是String自带的hashCode()方法,本来是件很方便的事,但是有些字符串取hashCode竟然是负数,使得分片为负数,找不到对应的分片,我们先看一下String 生成hashCode的代码:

/** * Returns a hash code for this string. The hash code for a * {@code String} object is computed as * <blockquote><pre> * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * </pre></blockquote> * using {@code int} arithmetic, where {@code s[i]} is the * <i>i</i>th character of the string, {@code n} is the length of * the string, and {@code ^} indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ 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; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpdjfx.html