在编写代码的过程中,我们经常会遇到当前的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
于是,得到如下结论: