String原始碼分析之equals和hashcode方法
阿新 • • 發佈:2019-01-30
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]