- 自定义类的equals方法使用的是object类中的equals方法,此时的equals方法相当于 == ,比较的是对象的地址
- 我们怎么样才能使equals方法比较的是属性的值是否相等呢? 比如String类比较的就是字符串的值是否相等
- 很简单,我们只需要在自定义类中重写equals方法即可。
- 若属性为引用数据类型,用equals方法判断,这个equals方法也是被重写过的。
public class MyDate {
private int year;
private int month;
private int day;
public MyDate(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}
public boolean equals(Object obj){
if(this == obj){
return true;
}
if(obj instanceof MyDate){
MyDate md = (MyDate) obj;
return this.year == md.year && this.month == md.month && this.day == md.day;
}else{
return false;
}
}
}
public class MyDateTest {
public static void main(String[] args) {
MyDate m1 = new MyDate(14, 3, 1976);
MyDate m2 = new MyDate(14, 3, 1976);
if (m1 == m2) {
System.out.println("m1==m2");
} else {
System.out.println("m1!=m2"); // m1 != m2
}
if (m1.equals(m2)) {
System.out.println("m1 is equal to m2");// m1 is equal to m2
} else {
System.out.println("m1 is not equal to m2");
}
}
}