Object类的equals方法

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;
	 }
	 */

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值