在編寫代碼的過程中,我們經常會遇到當前的equals和==之間的使用,但是,爲了弄懂當前的兩者之間的關係,我們將分析Object類中的equals方法 和 String類中的equals方法進行解析。
if (this == anObject) {
// 如果當前對象和傳進來要進行比較的對象anObject是同一個對象(即地址相同eg同一輛汽車(只有一輛))則返回true
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;
}
測試代碼如下:
private static void testEquals(){
int a = 5;
int b = 5;
System.out.println(a == b);
String aaString = new String("Hello");
String bbString = new String("Hello");
System.out.println(aaString == bbString);
System.out.println(aaString.equals(bbString));
System.out.println("------print the non string type -------");
Home homeA = new Home();
homeA.setDerection(1);
homeA.setPostion(1);
Home homeB = new Home();
homeB.setDerection(1);
homeB.setPostion(1);
System.out.println(homeA == homeB);
System.out.println(homeA.equals(homeB));
}
其中當前的Home類如下:
public class Home {
private int postion;
private int derection;
private volatile int hashCode;
public int getPostion() {
return postion;
}
public void setPostion(int postion) {
this.postion = postion;
}
public int getDerection() {
return derection;
}
public void setDerection(int derection) {
this.derection = derection;
}
}
打印結果如下:
true
false
true
------print the non string type -------
false
true
於是,得到如下結論: