为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

POPMUISE 2022-11-10 16:52:06
我看过其他时候在 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 时,它们都被错误地添加了。我知道我应该操纵我的哈希码函数,但我不知道该怎么做。
查看完整描述

1 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

您的定义equals意味着两个Inconsistency对象元素颠倒是.equalshashCodeabHashSet

解决这个问题的最简单方法是做一些可交换的事情——无论顺序a和顺序都具有相同的结果b。例如:

result = prime * result + a + b;

代替

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


查看完整回答
反对 回复 2022-11-10
  • 1 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号