Object类的equals方法
1)public boolean equals(Object obj) { return (this == obj); }提供定义对象是否“相等”的逻辑。
2)Object的equals方法定义为:x.equals(y)当x和y是“同一个”对象的应用时返回true否则返回false
3)J2SDK提供的一些类,如String,Date等,重写了Object的equals方法,调用这些类的equals方法,x.equals(y),当x和y所引用的对象是同一类对象且属性内容相等时(并不一定是相同对象),返回true否则返回false。
4)可以根据需要在用户自定义类型中重写equals方法。
知识链接:"=="和 equals 方法究竟有什么区别
==:运算符,适合于基本数据类型和引用数据类型。如果是基本数据类型,比较两个变量的值是否相等。 如果是引用数据类型变量,判断两个变量是否指向内存中的同一个对象(引用,内容都一样)。
equals():是 Object 类中定义过的一个方法。只适用于对象来调用。如果各个对象所在的类没有重写 Object 中的 equals(),则与==使用相同。如果所在的类重写了 equals(),一般重写的规则是判断两个对象中包含的所有属性的值是否相等。
/**
* 说明:未重写equals方法时候
* 如果各个对象所在的类没有重写 Object 中的 equals(),则与==使用相同。判断的是引用跟值都得相同
* @author huayu
* @date 2018/8/5 7:39 PM
*/
public class Dog {
int color;
int height,weight;
public Dog(int color, int height, int weight) {
this.color = color;
this.height = height;
this.weight = weight;
}
}
/**
* 说明:equals方法的测试类
*
* @author huayu
* @date 2018/8/5 7:41 PM
*/
public class TestEquals {
public static void main(String[] args) {
Dog dog=new Dog(1,2,3);
Dog dog1=new Dog(1,2,3);
System.out.println(dog==dog1);
System.out.println(dog.equals(dog1));
}
}
结果:
false
false
/**
* 说明:重写equals方法时候
* 如果所在的类重写了 equals(),一般重写的规则是判断两个对象中包含的所有属性的值是否相等。
* @author huayu
* @date 2018/8/5 7:39 PM
*/
public class Dog {
int color;
int height, weight;
public Dog(int color, int height, int weight) {
this.color = color;
this.height = height;
this.weight = weight;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
} else {
if (o instanceof Dog) {
Dog dog = (Dog) o;
if (dog.color == this.color && dog.height == this.height && dog.weight == this.weight) {
return true;
}
}
}
return false;
}
}
/**
* 说明:equals方法的测试类
*
* @author huayu
* @date 2018/8/5 7:41 PM
*/
public class TestEquals {
public static void main(String[] args) {
Dog dog=new Dog(1,2,3);
Dog dog1=new Dog(1,2,3);
System.out.println(dog==dog1);
System.out.println(dog.equals(dog1));
//下面验证第三条String类是否真的重写了equals方法
String string1=new String("hello");
String string2=new String("hello");
System.out.println("String判==结果: "+(string1==string2));
System.out.println("String判equals结果 "+(string1.equals(string2)));
}
}
结果:
false
true
String判==结果: false
String判equals结果: true