hashCode是java.lang.String类提供的方法(自从jdk1.0以来就有的),摘取关键的源码实现如下:
1、声明变量
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
2、hashCode方法的实现
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</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;
}
3、举例说明hashCode算法
4、例子中的说明
(1)0x7FFFFFFF介绍
F的二进制码为 1111
7的二进制码为 0111
0x是16进制的标识,0x7FFFFFFF代表十六进制的最高位是0,那么它与任何数做&运算都是正数。
(2)为什么要对hashcode做&运算
因为有些对象的hashcode的最大值会超过Int类型的最大值,为了避免出现负数,我们必须保证为正。
(3)hashCode的计算
为什么字符串"ABC"的HashCode是64578?
计算过程如下:
先确认字符的ASCII码,A=65、B=66、C=67
再利用公式
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
计算strHashCode=65*31^(3-1)+66*31^(3-2)+67*31^(3-3)=65*31^2+66*31+67=64578
参考:
http://blog.csdn.net/exceptional_derek/article/details/9074137
http://www.cnblogs.com/chenssy/p/3651218.html
http://blog.csdn.net/cwj649956781/article/details/8589981