String源码分析之equals和hashcode方法

时间:2021-12-16 16:09:52

1.说明

== :如果是非引用类型,则值相等;引用类型,则地址相同,也就是指向堆中相同的对象
equals:Object对象而言或者没有重写equals方法的类,等效于==;重写了equals方法则按子类的方法来比较

2.String的equals方法

2.1 先看代码

 public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}

2.2 解释

  • 如果两个对象的地址相同,那么equals返回true;
  • 如果两个对象类型不同,返回false;
  • 类型相同,先强制转换类型,先比较字符串长度,再注意比较

3.String的hashcode方法

3.1 先看代码

 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.2 解释

 /**
* 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.
*/

3.3 哈希值

  • 利用公式h=31*h+value[i]来生成哈希值
  • hashcode=s[0]*31^(n-1)+s[1]*31^(n-2)+…+s[n-1]