在<effective Java>中提到,一个好的散列函数通常倾向于"为不相等的对象产生不相等的散列码",下面是一个非常不错的散列函数:
public class Home {
private int postion;
private int derection;
private volatile int hashCode;
public int getPostion() {
return postion;
}
public void setPostion(int postion) {
this.postion = postion;
}
public int getDerection() {
return derection;
}
public void setDerection(int derection) {
this.derection = derection;
}
@Override
public boolean equals(Object obj) {
if(null == obj){
return false;
}
if(this == obj){
return true;
}
if(obj instanceof Home){
Home home = (Home) obj;
if(home.getDerection()== this.getDerection() &&
home.getPostion() == this.getPostion()){
return true;
}
}
return super.equals(obj);
}
@Override
public int hashCode() {
int result = hashCode;
if(result == 0){
result = 17 ;
result = 31*result + postion;
result = 31*result + derection;
hashCode = result;
}
return result;
}
}