java的equals方法重写注意事项

来源:互联网 发布:php自动加载机制 编辑:程序博客网 时间:2024/04/30 08:16

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 stubout.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 {@Overridepublic 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))));}@Overridepublic Employee clone() throws CloneNotSupportedException {return (Employee)super.clone();}private String name;private double salary;private Date hireDay;}class Manager extends Employee {@Overridepublic 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
原创粉丝点击