我有这个类...什么是一个整数元组的好散列函数?
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