62,624
社区成员
发帖
与我相关
我的任务
分享
/**
* 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;
}
可以看到,String的hashCode的计算方法就是将每个字符进行hash * 31 + charAt(i)的方式进行迭代。当然,最终的值会受每个字符的影响啦(大写字母与小写字母的字符值不一样)。
hashCode与equals是成对出现的,也就是说,hashCode不同,equals必然不同。但是,hashCode相同,equals也有可能不同。
另外,对于没有实现equals的对象,会默认使用Object.equals,该方法是在jvm里实现的,跟对象的内存地址,当前系统状态等等都有关系,同样,这个hashCode值也会遵守上述的原则。