0

我有这个课...

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和另一个对象中时才定义此类对象之间的相等性。iStopiStartiStop

所以既然我已经覆盖equals()了,我需要覆盖,hashCode()但我不确定如何为这个类定义一个好的散列函数。iStart使用and为此类创建哈希码的好方法是什么iStop

4

3 回答 3

2

来自 Bloch 的“Effective Java”:

int iHashCode = 17;
iHashCode = 31 * iHashCode + iStart;
iHashCode = 31 * iHashCode + iStop;

注意:选择 31 是因为 VM 可以将 31 的乘法优化为位操作。(但性能在您的情况下没有用,因为正如@Ted Hopp 所提到的,您只计算一次值。)

注意:如果iHashCode翻过最大的int.

于 2011-06-06T00:30:03.547 回答
2

我很想使用它,特别是因为你要记住它:

Long.valueOf((((long) iStart) << 32) | istop)).hashcode();
于 2011-06-06T00:30:05.020 回答
2

最简单的可能是最好的

iHashCode = iStart^iStop;

两个值的异或

请注意,当开始和停止交换时,这将给出相等的哈希码

作为另一种可能性,你可以做

iHashCode = ((iStart<<16)|(iStart>>>16))^iStop;

第一个桶移位从 16 开始,然后 xor 随之停止,因此最低有效位被放在 xor 中(如果 start 永远不大于 65k(更准确地说是 2^16),您可以省略该(iStart>>>16)部分)

于 2011-06-06T00:36:30.247 回答