哈希集没有意识到两个对象是相同的



我已经看过其他时候在stackoverflow上问了这个问题,但是其他用例似乎都无法解决我的问题。哈希集似乎没有意识到两个对象是相同的。

基本上,这是我的班级。

private static class Inconsistency
    {
        int a;
        int b;
        boolean isConsistency;

        //Default constructor. To be used when we don't have an inconsistency
        public Inconsistency()
        {
            this.a = -1;
            this.b = -1;
            this.isConsistency = false;
        }
        public Inconsistency(int a, int b, boolean isConsistency)
        {
            this.a = a;
            this.b = b;
            this.isConsistency = isConsistency;
        }
        @Override
        public String toString()
        {
            if (this.isConsistency) 
            {
                return "(" + this.a + ", " + this.b + ")";
            } 
            else 
            {
                return "No inconsistency";
            }
        }
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + a;
            result = prime * result + b;
            result = prime * result + (isConsistency ? 1231 : 1237);
            return result;
        }
        @Override
        public boolean equals(Object other)
        {
            if (this == other)
            {
                return true;
            }
            if (other == null)
            {
                return false;
            }
            if (this.getClass() != other.getClass()) 
            { 
                return false; 
            }
            Inconsistency otherInconsistency = (Inconsistency) other;
            return ((this.a == otherInconsistency.a) && (this.b == otherInconsistency.b) && (this.isConsistency == otherInconsistency.isConsistency))
                || ((this.a == otherInconsistency.b) && (this.b == otherInconsistency.a) && (this.isConsistency == otherInconsistency.isConsistency));
        }
    }

我正在尝试将班级的对象存储在哈希图中。

通过我定义我的平等方法的方式,不一致a(10,20,true(应等于另一个不一致的b(20,10,true(,当我测试我的等值方法时,这是正确的。但是,当我尝试将A和B插入标签中时,它们都会错误地添加。我知道我应该操纵我的哈希码功能,但我不确定该如何处理。

这是一个驱动程序,展示了错误的行为

    Inconsistency A = new Inconsistency(10,20, true);
    Inconsistency B = new Inconsistency(20,10, true);
    System.out.println(A.equals(B)); // prints true as expected

    HashSet<Inconsistency> test = new HashSet<>();
    test.add(A);
    test.add(B);
    System.out.println(test); // prints [(10, 20), (20, 10)]. The two objects are equal but are both added to hashset

就是这样一个问题,我该如何确保两个相等的对象A和B都不会添加到我的标签中?

您对 equals的定义意味着两个 Inconsistency具有反转元素的对象是 .equals,但是您对 hashCode的定义dome not> not> not 如果ab,则返回相同的哈希代码按不同的顺序,如果HashSet或其他基于哈希的集合要正常工作。

解决此问题的最简单方法是做一些交通证的事情 - 与ab的顺序相同的结果。例如:

result = prime * result + a + b;

而不是

result = prime * result + a;
result = prime * result + b;

最新更新