为具有“可互换”字段的对象实现哈希码

Jam*_*mes 5 java hashcode

如果“第一个”和“第二个”交换,我希望 Pair 类的两个实例被视为相等,即 Pair(1,2) == Pair(2,1) 应该评估为 true。

    static class Pair {
        int first;
        int second;

        Pair(int first, int second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj == null || obj.getClass() != this.getClass()) {
                return false;
            }

            Pair that = (Pair) obj;
            return (this.first == that.first && this.second == that.second)
                    || (this.second == that.first && this.first == that.second);
        }

        @Override
        public int hashCode() {
            return Objects.hash(first, second) + Objects.hash(second, first);

        }
    }
Run Code Online (Sandbox Code Playgroud)

我想出了这个 hashcode(),它似乎有效,但是有没有更好/普遍接受的方法来做到这一点?

Kar*_*cki 4

没有开销的更简单的哈希码Objects.hash()是:

@Override
public int hashCode() {
  return first + second;
}
Run Code Online (Sandbox Code Playgroud)

它与Integer.hashCode()返回Integer值类似。

  • @FazoM `hashCode()` 不是相等检查,那是 `equal()` 工作。这些方法具有契约,并且哈希码相等并不意味着对象相等。 (3认同)
  • `first ^ Second` 会做得稍微好一点,在信息上损失一点溢出。然而 2^1 正好等于 3^0。但不是 2^4 和 3^3。 (2认同)
  • @FazoM 阅读 https://vanilla-java.github.io/2018/08/15/Looking-at-randomness-and-performance-for-hash-codes.html (2认同)
  • @JoopEggen因此,对于两个输入在整个值空间上的相等分布,两者都会在值空间上产生相等的结果分布。很容易证明这适用于所有位大小。但实际上,较小的数字比较大的数字更有可能出现,并且应用领域的范围不是 2 的幂。在这些情况下(相关情况),异或根本不使用高位,这使得它比加更糟糕。 (2认同)