java equals注意什么_java的equals方法重写注意事项

java的equals方法一般情况下需要重写,以保证能够比较两个实例对象是否一致。

package chap09;

import static java.lang.System.out;

import java.util.Date;

public class EqualsTest {

public static void main(String[] args) {

// TODO Auto-generated method stub

out.println("successful");

Employee e1 = new Employee();

Employee e2 = new Employee();

out.println(e1 == e2);

out.println(e1.hashCode());

out.println(e2.hashCode());

}

}

class Employee implements Cloneable {

@Override

public boolean equals(Object obj) {

/**

* equals must five steps:

* 1:two variable are point to the same object.

* 2:obj is null.

* 3:variables is the same Class.

* 4:cast obj.

* 5:equals each field's value(== for primitive; equals for object).

* */

if (this == obj) {

return true;

}

if ((obj == null) && (this.getClass() != obj.getClass())) {

return false;

}

Employee other = (Employee)obj;

return ((this.name.equals(other.name) &&

(this.salary == other.salary) &&

(this.hireDay.equals(other.hireDay))));

}

@Override

public Employee clone() throws CloneNotSupportedException {

return (Employee)super.clone();

}

private String name;

private double salary;

private Date hireDay;

}

class Manager extends Employee {

@Override

public boolean equals(Object obj) {

/**

* derived class's equals method have three steps to equals two objects.

* 1:call the super object to equals with obj.

* 2:cast obj.

* 3:each field value, which are added in this class.

* */

if ( !super.equals(obj)) {

return false;

}

Manager other = (Manager)obj;

return (this.bonus == other.bonus);

}

private double bonus;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值