一、背景
在java中的equals和==比較規則:
" == "在基本數據類型:比較值內容 引用類型時:比較地址
equals 重寫:比較值內容 , equals不重寫:比較地址
那麼Java中的一些常用類型,對equals是否進行重寫,如果進行了重寫,則實現了怎麼的邏輯?
二、equals函數重寫
2.1 String
String作爲引用類型,==直接比較地址。String類重寫equals函數,源碼如下:
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;
}
String類的底層實現爲final類型的char[],可見String的equals函數比較的是字符串的值是否想等。
2.2 Integer等對象包裝器
有時需要將基本類型,例如int轉換爲對象,所有的基本類型都有一個與之對應的類,這些類統稱包裝器。這些包裝器都有很明顯的名字,Integer、Long、Float、Double、Short、Byte、Character、Boolean。
這些包裝器重寫的equals函數大同小異,其中Integer的equals函數如下:
/**
* Compares this object to the specified object. The result is
* {@code true} if and only if the argument is not
* {@code null} and is an {@code Integer} object that
* contains the same {@code int} value as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same;
* {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
如上,Integer的equals函數會將Integer拆箱比較保存的基本類型值。
2.3 AbstractList