Java 語言裏的 equals方法其實是交給開發者去覆寫的,讓開發者自己去定義滿足什麼條件的兩個Object是equal的。
所以我們不能單純的說equals到底比較的是什麼。你想知道一個類的equals方法是什麼意思就是要去看定義。
Java中默認的 equals方法實現如下:
public boolean equals(Object obj) {
return (this == obj);
}
而String類則覆寫了這個方法,直觀的講就是比較字符是不是都相同。
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}