我有這個類...什麼是一個整數元組的好散列函數?
public class StartStopTouple {
public int iStart;
public int iStop;
public int iHashCode;
public StartStopTouple(String start, String stop) {
this.iStart = Integer.parseInt(start);
this.iStop = Integer.parseInt(stop);
}
@Override
public boolean equals(Object theObject) {
// check if 'theObject' is null
if (theObject == null) {
return false;
}
// check if 'theObject' is a reference to 'this' StartStopTouple... essentially they are the same Object
if (this == theObject) {
return true;
}
// check if 'theObject' is of the correct type as 'this' StartStopTouple
if (!(theObject instanceof StartStopTouple)) {
return false;
}
// cast 'theObject' to the correct type: StartStopTouple
StartStopTouple theSST = (StartStopTouple) theObject;
// check if the (start,stop) pairs match, then the 'theObject' is equal to 'this' Object
if (this.iStart == theSST.iStart && this.iStop == theSST.iStop) {
return true;
} else {
return false;
}
} // equal() end
@Override
public int hashCode() {
return iHashCode;
}
}
...我定義一個對象,對象之間只有iStart
和iStop
平等是在其他對象等於iStart
和iStop
。
因此,由於我已覆蓋equals()
,我需要覆蓋hashCode()
,但我不確定如何爲此類定義好的散列函數。使用iStart
和iStop
創建這個類的哈希代碼的好方法是什麼?
一個簡單的「桶式散列散列」就足夠了。應該幫助SO搜索。 HashMap和類似的實際上會重新散列散列值,所以偶數分佈並不是非常重要。 – 2011-06-06 00:28:34
@pst ...你介意提供一些示例代碼嗎? – Hristo 2011-06-06 00:29:37
這取決於'iStart'和'iStop'值的分佈 - 如果它們介於'0-9'之間,那麼'iStart * 10 + iStop'可能會很好。那麼,你期待什麼範圍的輸入? – sarnold 2011-06-06 00:29:38