在Object 类中定义有:
1、public boolean equals(Object object )方法提供定义对象是否“相等”逻辑。
2、Object的equals方法定义为:x.equals(y)当x和y是同一个对象的引用时,返回true,否则返回false
3、在其他一些类中,例如String Date等,重写了Object的equals方法,调用这些类的equals方法,当x和y所引用的对象是同一类对象且属性内容相等时
(并不一定是相同对象),return true; 否则的话,return false;
4、当然,可以根据需要在用户自己定义重写equal方法。
举例:
public class TestEquals{
public static void main(String[] args) {
Cat c1 = new Cat(1,2,3);
Cat c2 = new Cat(1,2,3);
System.out.println(c1 == c2);//false
System.out.println(c1.equals(c2));//true
}
}
class Cat{
int color;
int height,weight;
public Cat(int color, int height, int weight){
this.color = color;
this.height = height;
this.weight = weight;
}
public boolean equals(Object obj){
if(obj == null) return false;
else{
if(obj instanceof Cat){/*if obj is a object of Cat ,return true ,else if obj is not a object of Cat or is null,return flase*/
Cat c = (Cat)obj;
if(c.color == this.color && c.height == this.height && c.weight == this.weight)
return true;
}
}
}
return false;
}
运行结果:
false
true