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。

你可能感兴趣的:(Java基础,Java)