HashSet没有意识到两个对象是相同的

时间:2019-05-06 22:03:06

标签: java hashset

我看过其他时候在StackOverflow上问过这个问题,但是其他用例似乎都不能解决我的问题。 HashSet does not seem to realize that two objects are the same.

基本上,这是我的课程。

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));
        }
    }

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

使用我定义equals方法的方式,不一致A(10,20,true)应该等于另一个不一致B(20,10,true),当我测试我的equals方法时,这可以正常工作。但是,当我尝试将A和B都插入到HashSet中时,它们都被错误地添加了。我知道我应该操纵我的哈希码功能,但不确定如何去做。

这里有个司机展示了错误的行为

    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都不会添加到我的HashSet中?

1 个答案:

答案 0 :(得分:6)

您对equals的定义意味着两个元素颠倒的Inconsistency对象是.equals,但是您对hashCode的定义 not 返回如果ab的顺序不同,则使用相同的哈希码,如果HashSet或其他基于哈希的集合可以正常工作,则这是必需的。

解决此问题的最简单方法是进行可交换的操作-不论输入ab的顺序具有相同的结果。例如:

result = prime * result + a + b;

代替

result = prime * result + a;
result = prime * result + b;
相关问题