重写equals和hasCode 方法 JDK1.7



import java.io.Serializable;
import java.util.Objects;
/**
 * 联合主键类 必须实现Serializable接口
 * 重新equals()和hasCode()方法
 * 
 * @author wxl
 *
 */
public class ScoreId implements Serializable{
/**

*/
private static final long serialVersionUID = 1L;
private int stuId; //学生id
private int subjectId;//科目编号
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public int getSubjectId() {
return subjectId;
}
public void setSubjectId(int subjectId) {
this.subjectId = subjectId;
}
/**
* 重新hashCode方法
*/
@Override
public int hashCode() {
return Objects.hash(stuId,subjectId);
}
/**
* 重写Object的equals方法

* java核心技术 第九版
* page 171

* 1.显示参数命名为otherObj,方法中需要将它转换成另一个叫做other的变量
*/
@Override
public boolean equals(Object otherObj) {
//2. 检查 this和otherObj是否指向同一个对象 优化语句
if(this == otherObj) { return true;}
//3. 检测otherObj是否为空 如果为null 返回false
if(otherObj == null) { return false;}
//4. 比较this 和 otherObj 是否属于同一个类,不是返回false
//如果equals 的语义在每个子类中有所改变,就使用getClass检查
if(getClass() != otherObj.getClass()) { return false;}
//如果所有的子类都拥有统一的语义,就是使用instanceof 检查
if(!(otherObj instanceof ScoreId)) { return false;}
//5. 将otherObj转化成相应的类类型变量
ScoreId other = (ScoreId) otherObj;
   //6. 开始对所有的属性进行比较,使用 == 比较基本类型属性,
// 使用equals 比较对象属性,如果所有的属性都匹配返回true,否则返回false
return stuId == other.stuId 
&& this.subjectId == other.subjectId;
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值