猿问

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

我看过其他时候在 StackOverflow 上问过这个问题,但其他用例似乎都没有解决我的问题。HashSet 似乎没有意识到两个对象是相同的。


基本上,这是我的课。


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;

            }



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


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


POPMUISE
浏览 78回答 1
1回答

MMTTMM

您的定义equals意味着两个Inconsistency对象的元素颠倒是.equalshashCodeabHashSet解决这个问题的最简单方法是做一些可交换的事情——无论顺序a和顺序都具有相同的结果b。例如:result = prime * result + a + b;代替result = prime * result + a; result = prime * result + b;
随时随地看视频慕课网APP

相关分类

Java
我要回答