**
重写 equals 以及 hashCode 方法
**
- hashCode & equals:
在Object类中,hashCode()返回的是根据对象的存储地址计算出来一个哈希值,equals()是判断两个对象的内存地址是否相等。**所以hashCode主要是用于查找使用的,而equals()是用于比较两个对象是否相等的。**但当需要重写这两个方法时,需要注意三点:
如果两个对象的equals()结果为true,那么这两个对象的hashCode一定相同
两个对象的hashCode()结果相同,并不能代表两个对象的equals()一定为true,只能够说明这两个对象在一个散列存储结构中
如果对象的equals()被重写,那么对象的hashCode()也要重写(若只重写两个方法中的一个,都无无法保证唯一性)
元素放入Set的流程:
假设只重写了hashCode方法:
不同地址的对象也许会有相同的hashcode值,但在equals判断时,仍然比较了对象的地址值,那么还是会被认定为不同的对象,被放入对象。
假设只重写了equals方法:
任何不同的对象的hashCode方法得出的哈希值都将不同(返回的是对象的存储地址,而不同对象的内存地址永远是不同的),在唯一性判断时都将直接被放入对象,而进不到equals的判断。
重写代码如下
equals 方法
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if(!(obj instanceof User)) {
return false;
}
User other = (User)obj;
if(id != other.id) {
return false;
}
if(age != other.age) {
return false;
}
if(name.equals(other.name)) {
return false;
}
if(!gender.equals(other.gender)) {
return false;
}
if(!birthday.equals(other.birthday)) {
return false;
}
return true;
}
重写hashCode() 方法 代码如下
public int hashCode() {
int result;
result = getName().hashCode();
result = 29 * result + getBirthday().hashCode();
result = 29 * result + getAge();
return result;
}