1.sun公司设计equals 方法的目的
判断两个对象是否相等
2.判断两个基本数据类型是否相等直接使用”“就可以了。“”比较的是内存地址,不能用于判断两个java对象是否相等
equals方法默认使用"=="进行比较,我们应该判断两个java对象的内容是否相等,所以需要子类重写equals方法
基本数据类型
package day20;
public class Test02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 100;
int b = 100;
System.out.println(a==b);
}
}
true
重写equals
(简洁版)
public boolean equals(Object obj) {
if(obj == null || !(obj instanceof MyTime)) {
return false;
}
if(this==obj) {
return true;
}
MyTime t = (MyTime)obj;
return this.year == t.year && this.month==t.month && this.day==t.day;
}
(过程版)
package day20;
public class MyTime {
int year;
int month;
int day;
public MyTime() {
}
public MyTime(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
//重写toString方法
//public String toString() {
// return this.year + "年" + this.month+ "月"+ this.day + "日";
//}
//重写equals方法
/*public boolean equals(Object obj) {
//当年,月,日相等时,表示两个日期相同。两个对象相等。具体的判断条件需要自己设置
//(相等的条件代码)
//获取第一个日期的年月日
int year1 = this.year;
int month1 = this.month;
int day1 = this.day;
//获取第二个日期的年月日
//(获取第二个日期时,year,month,day自在字类中有,Object父类不能直接访问字类,要强制向下转型)
if(obj instanceof MyTime) {
MyTime t = (MyTime)obj;
int year2 = t.year;
int month2 = t.month;
int day2 = t.day;
if(year1 == year2 && month1 == month2 && day1 == day2) {
return true;
}
}
//程序能执行到此处表示日期不相等
return false;
*/
//改良equals方法
public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(!(obj instanceof MyTime)) {
return false;
}
//如果this和obj是同一个对象,那么内存地址也相同
if(this == obj) {
return true;
}
//程序能执行到此处说明obj不是null,obj是MyTime类型
MyTime t = (MyTime)obj;
/*
if(year == t.year && month == t.month && day == t.day) {
return true;
}
//程序能到这里返回false
return false;
*/
//再次改良
return year == t.year && month == t.month && day == t.day;
}
/*
public boolean equals(Object obj) {
if(obj == null || !(obj instanceof MyTime)) {
return false;
}
if(this==obj) {
return true;
}
MyTime t = (MyTime)obj;
return this.year == t.year && this.month==t.month && this.day==t.day;
}
*/
}