java 的Object的equals方法

/** 
*  
*/  
package freewill.objectequals;  
  
/** 
* @author freewill 
* @see Core Java page161 
* @desc getClass实现方式,另有instance of实现方式,根据不同场景使用。 
*/  
public class Employee {  
    private String name;  
    private int salary;  
    private String hireDay;  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public int getSalary() {  
        return salary;  
    }  
  
    public void setSalary(int salary) {  
        this.salary = salary;  
    }  
  
    public String getHireDay() {  
        return hireDay;  
    }  
  
    public void setHireDay(String hireDay) {  
        this.hireDay = hireDay;  
    }  
  
    @Override  
    public boolean equals(Object obj) {  
        // a quick test to see if the objects are identical  
        if (this == obj)  
            return true;  
        // must return false if the explicit parameter is null  
        if (obj == null)  
            return false;  
        // if the class don't match,they can't be equal  
        if (getClass() != obj.getClass())  
            return false;  
        // now we know obj is non-null Employee  
        Employee other = (Employee) obj;  
        // test whether the fileds have identical values  
        return name.equals(other.name) && salary == other.salary  
                && hireDay.equals(other.salary);  
    }  
  
}  


Java语言规范要求equals方法具有下面的特性: 
1.自反性:对于任何非空引用x,x.equals(x)应该返回true。 
2.对称性:对于任何引用x和y,当且仅当y.equals(x)返回true,x.equals(y)也应该返回true。 
3.传递性:对于任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,x.equals(z)也应该返回true。 
4.一致性:如果x和y引用的对象没有发生变化,反复调用x.equals(y)应该返回同样的结果。 
5.对于任意非空引用x,x.equals(null)应该返回false。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值