【Core Java Volume1】重写equals,hashCode,toString方法

本文详细介绍如何在Java中正确地重写equals(), hashCode() 和 toString() 方法,以确保对象的正确比较、哈希和展示。包括使用Objects类简化比较过程、确保子类与父类的一致性以及提供有意义的对象字符串表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 重写equals()方法:

例:重写父类Employee3的equals方法

//重写equals
	//1 显示命名参数otherObject,稍后转化为other
	public boolean equals(Object otherObject){
		//2 检测this与 otherObject 是否引用同一个对象
		if(this == otherObject) return true;
		//3 检测otherObject 是否为null
		if(otherObject == null) return false;
		// 4 比较this与 sotherObject 是否为同一个类
		if(getClass()!= otherObject.getClass())
			return false;
		//5 转化
		Employee3 other =(Employee3)otherObject;
		//比较,基本类型的就用==比较
		return Objects.equals(name, other.name) && salary ==other.salary 
			&& Objects.equals(hireDate, other.hireDate);
	}
子类Manager3继承Employee3,其重写的equals()方法如下:

<span style="white-space:pre">	</span>public boolean equals(Object otherObject){
		if(! super.equals(otherObject))
			return false;
		
		Manager3 other =(Manager3)otherObject;
		return bonus == other.bonus;
	}

2 重写HashCode()方法:

父类:

//重写hashCode
	public int hashCode(){
		return Objects.hash(name,salary,hireDate);
	}
子类:

<span style="white-space:pre">	</span>public int hashCode(){
		return super.hashCode() + 17*new Double(bonus).hashCode();
	}


3 重写toString()方法:返回对象值的字符串,最好通过调用getClass().getName()获得类名的字符串


父类:

//重写toString
	public String toString(){
		return getClass().getName()+"[name="+name+",salary="+salary+",hireDate="+hireDate+"]";
	}
子类:

	public String toString(){
		return super.toString()+"[bonus="+bonus+"]";
	}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值