[Java Core]Java类的equals方法的实现

本文详细阐述了Java中equals方法的要求及一个完善的比较类实现,包括自反性、对称性、传递性、一致性及非空结果等关键点。

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

Java对equals方法的要求:

1. 自反性:x.equals(x) == true

2. 对称性:x.equals(y) == y.equals(x)

3. 传递性:

x.equals(y) == true && y.equals(z) == true   =>    x.equals(z) == true

4. 一致性:若x,y均没有发生变化,x.equals(y)的结果不论调用多少次,都不发生变化

5. 非空结果:x.equals(null) == false


依据这几点要求,书中给出了一个完善的比较类的方法:

import java.util.Objects;  
  
public class Employee {  
    public String member;  
    public Object obj;  
    public Employee(final String Member, final Object Obj){  
        member = Member;  
        obj = Obj;  
    }  
    public boolean equals(Object otherObj){  
          
        //refer to same object, return true  
        if(this == otherObj) return true;  
          
        //otherObj is null, return false  
        if(otherObj == null) return false;  
          
        //belong to different class, return false  
        if(this.getClass() != otherObj.getClass()) return false;  
          
        //solve the problem of comparison between super obj and child obj  
        if(!(otherObj instanceof Employee)) return false;  
          
        Employee other = (Employee)otherObj;  
          
        //in case obj or other.obj is null  
        return Objects.equals(obj, other.obj)  
            && member.equals(other.member);  
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值