}看源码,我们可以发现,这个比较分为两部分
1.先比较是否引用同一对象
2.如果引用对象不同,是否两个String的content相同
3,String 类的hashcode 方法
* Returns a hash code for this string. The hash code for a *Stringobject is computed as ** using* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] *intarithmetic, wheres[i]is the * ith character of the string,nis the length of * the string, and^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; } /** * Returns a hash code for this string. The hash code for a *Stringobject is computed as ** using* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] *intarithmetic, wheres[i]is the * ith character of the string,nis the length of * the string, and^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;
}可以看到hashcode的计算公式为:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
因此,对于同一个String,得出的hashcode必然是一致的
另外,对于空的字符串,hashcode的值是0
小结
至此,我们可以对本文开头的疑问做一个小结.
1.字符串比较时用的什么方法,内部实现如何
使用equals方法,先比较引用是否相同,后比较内容是否一致.
2.hashcode的作用,以及重写equal方法,为什么要重写hashcode方法
hashcode是系统用来快速检索对象而使用,equals方法是用来判断引用的对象是否一致,所以,当引用对象一致时,必须要确保其hashcode也一致,因此需要重写hashcode方法来确保这个一致性
1.字符串比较时用的什么方法,内部实现如何
2.hashcode的作用,以及重写equal方法,为什么要重写hashcode方法