Java HashSet 包含返回 false,即使覆盖了 equals() 和 hashCode()

NoB*_*ect 5 java contains equals hashcode hashset

我像这样初始化 HashSet:

private HashSet<Rule> ruleTable = new HashSet<Rule>();
Run Code Online (Sandbox Code Playgroud)

我的对象(抽象类的子类)的equals()hashCode()方法如下所示:TcpRuleRule

@Override
public int hashCode() {
    // Ignore source Port for now
    return (this.getSrcPool() + ":" + this.getDstPool() + ":" + this.getProtocol() + ":" + this.dstTcp).hashCode();
}

@Override
public boolean equals(Object obj) {
    if (!(obj instanceof TcpRule))
        return false;
    if (obj == this)
        return true;

    TcpRule r = (TcpRule) obj;
    return (this.getSrcPool().equals(r.getSrcPool()) && this.getDstPool().equals(r.getDstPool()) && this.getProtocol().equals(r.getProtocol()) && this.getSrcTcp() == r.getSrcTcp() && this.getDstTcp() == r.getDstTcp());
}
Run Code Online (Sandbox Code Playgroud)

我什至写了一个简单的单元测试,它没有给出任何错误:

@Test
public void equalsTest() {
    Pool srcPool = new Pool("PROXY");
    Pool dstPool = new Pool("WEB");
    int srcTcp = 54321;
    int dstTcp = 80;

    TcpRule r1 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
    TcpRule r2 = r1;
    assert r1.equals(r2);

    TcpRule r3 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
    TcpRule r4 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
    assert r3.equals(r4);
}

@Test
public void hashCodeTest() {
    Pool srcPool = new Pool("PROXY");
    Pool dstPool = new Pool("WEB");
    int srcTcp = 54321;
    int dstTcp = 80;

    TcpRule r1 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
    TcpRule r2 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
    assert r1.hashCode() == r2.hashCode();

    HashSet<Rule> rules = new HashSet<Rule>();
    rules.add(r1);
    assert rules.contains(r1);

    assert rules.contains(r2);
}
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,我有一个add()方法,我只需将一个Rule对象添加到HashSet

@Override
public void add(Rule rule) {
    ruleTable.add(rule);
}
Run Code Online (Sandbox Code Playgroud)

在另一种方法中,我检查规则中是否存在HashSet

    @Override
public boolean isPermittedTcp(IpAddress sourceAddress, IpAddress destinationAddress, short srcTcp, short dstTcp) {
    Pool sourcePool = poolService.getPool(new Host(sourceAddress));
    Pool destinationPool = poolService.getPool(new Host(destinationAddress));
    Rule r = new TcpRule(sourcePool, destinationPool, srcTcp, dstTcp);
    log.info("Checking: " + r.toString());
    log.info("Hash-Code: " + r.hashCode());
    log.info("Hashes in ruleTable:");
    for(Rule rT : ruleTable) {
        log.info("" + rT.hashCode());
    }
    if(ruleTable.contains(r)) {
        log.info("Hash found!");
    } else {
        log.info("Hash not found!");
    }
    return ruleTable.contains(r);
}
Run Code Online (Sandbox Code Playgroud)

日志消息表明Rule对象 ( r.hashCode())的散列是-1313430269,并且HashSet(rT.hashCode()在循环中) 中的一个散列也是-1313430269。但ruleTable.contains(r)总是返回false。我究竟做错了什么?

我在 StackOverflow 上发现了类似的问题,但这些问题主要涉及没有(正确)覆盖的equals()orhashCode()方法。我想我已经正确地实现了这两种方法。

6to*_*ton -1

您在 equals this.getSrcTcp() == r.getSrcTcp() 中有一个额外的条件,它不是哈希代码的一部分 - 也许这就是问题,哈希代码是相同的,但 equals 是 false。检查此字段与您正在比较的值是否不同。

尽管有评论,我认为这不起作用的原因是因为 equals 和 hashCode 实现不使用相同的字段。

模拟问题的代码:

import java.util.HashSet;

/**
 * @author u332046
 *
 */
public class HashCodeCollisionTest {
    public static class KeyDemo {
        String id;

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((id == null) ? 0 : id.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            /*if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            KeyDemo other = (KeyDemo) obj;
            if (id == null) {
                if (other.id != null)
                    return false;
            } else if (!id.equals(other.id))
                return false;
            return true;*/
            return false;
        }

        public KeyDemo(String id) {
            super();
            this.id = id;
        }
    }

    static HashSet<KeyDemo> set = new HashSet<>();

    public static void main(String[] args) {
        set.add(new KeyDemo("hi"));
        set.add(new KeyDemo("hello"));

        System.out.println(set.contains(new KeyDemo("hi")));
    }
}
Run Code Online (Sandbox Code Playgroud)

这打印false. 取消注释等于代码并打印true

  • 你还没有证明你认为你已经证明的事情。你的“equals”方法*总是*返回“false”,所以显然它永远不会打印“true”。更好的测试是取消注释“equals”中的所有代码,但使“hashCode()”返回 0 - 因此*所有*实例的值相同。 (2认同)
  • 另请阅读“Object.hashCode”的文档:“*不*要求如果两个对象根据 equals(java.lang.Object) 方法不相等,则对两个对象中的每一个调用 hashCode 方法必须产生不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同的整数结果可能会提高哈希表的性能。 (2认同)