equals是超類object提供的方法,基于實際記憶體位址判斷。hashcode是将實際記憶體位址通過hash算法得出的值
那麼也就意味着如果兩個引用變量通過equals判斷結果為true,那麼hashcode值也必然相等。
假設給定一個Student類,在這個類中隻重寫了equals方法,沒有重寫hashcode方法
package com.polymophic;
public class Student {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, String sex, int age) {
super();
this.name = name;
this.sex = sex;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
return true;
}
}
寫一個測試類進行判斷
public static void main(String[] args) {
Student student = new Student("Bill", "female", 22);
Student student2 = new Student("Bill", "female", 22);
System.out.println("student的hashcode值:" + student.hashCode());
System.out.println("student2的hashcode值:" + student2.hashCode());
System.out.println(student.equals(student2));
}
傳回結果為:
但是想想,equals在判斷引用資料類型時(除去String類型)是基于實際記憶體位址,那麼傳回值為true表示兩個對象是相同的,為什麼hashcode值卻不相同呢?這就是因為沒有重寫hashcode方法導緻的
那在Student類中加上hashcode方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
在進行測試發現:
沖突解決了
總結下:
equals方法與hashcode方法必須一起重寫的原因是:解決equals傳回結果與hashcode值不同之間的沖突