1. 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。
2. 如果重写equals方法,就必须重写hashCode方法,并且:如果x.equals(y)返回true,那么x.hashCode()就必须与y.hashCode()具有相同的值。
3. 编写equals方法的建议:
package com.huey.demo;
import java.util.Date;
public class Student {
private int number;
private String name;
private Date birthday;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Student() {
}
public Student(int number, String name, Date birthday) {
setNumber(number);
setName(name);
setBirthday(birthday);
}
@Override
public int hashCode() {
return name.hashCode() * 11 + birthday.hashCode();
}
@Override
public boolean equals(Object otherObject) {
// 检测this和otherObject是否引用同一对象;
// 这只是一个优化,计算等式要比一个一个地比较类中所有域所付出的代价小得多
if (this == otherObject)return true;
// 如果otherObject为null,返回false
if (otherObject == null) return false;
// 如果equals的语义在每个子类中有所改变,就使用getClass检测
if (getClass() != otherObject.getClass()) return false;
// 如果所有的子类都拥有统一的语义,就使用instanceof检测
// if (!(otherObject instanceof Student)) return false;
// 将otherObject转换为相应的类类型变量
Student other = (Student)otherObject;
// 对需要比较的域进行比较
return number == other.getNumber()
&& name.equals(other.getName())
&& birthday.equals(other.getBirthday());
}
}