一:看第一个例子
public class Cat1 {
private String color;
private int height;
private int weight;
Cat1(String color, int height, int weight) {
this.color = color;
this.height = height;
this.weight = weight;
}
public static void main(String[] args) {
Cat1 cat1 = new Cat1("red", 1, 2);
Cat1 cat2 = new Cat1("red", 1, 2);
System.out.println(cat1 == cat2);
System.out.println(cat1.equals(cat2));
}
}
输出结果:
false
false
cat1 == cat2 很简单,他们不是同一对象,有不通的存储地址。
但是cat1.equals(cat2)为什么是false呢。因为cat是对象,这里用的是父类的equals方法
而Object类equals方法的实现为:
<strong><span style="font-size:18px;"> public boolean equals(Object obj) {
return (this == obj);
}</span></strong>
所以,Obejct的equals方法本质上还是用==比较的。
二:尝试重写Obejct的equals方法
public class Cat2 {
private String color;
private int height;
private int weight;
Cat2(String color, int height, int weight) {
this.color = color;
this.height = height;
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
/**
* 重写Object的equals方法
*/
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj instanceof Cat2) {
Cat2 catObj = (Cat2) obj;
if (catObj.getColor() == this.color
&& catObj.getHeight() == this.height
&& catObj.getWeight() == this.weight) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Cat2 cat1 = new Cat2("red", 1, 2);
Cat2 cat2 = new Cat2("red", 1, 2);
System.out.println(cat1.equals(cat2));
}
}
输出结果:
true
三:String的equals方法
String s1 = "abc";
String s2 = "abc";
System.out.println(s1.equals(s2));
具体重写实现为:
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;
}
版权声明:本文为u013628152原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。