【问题标题】:What happen if hascode function is false while equal function is true如果 hascode 函数为 false 而 equal 函数为 true 会发生什么
【发布时间】:2019-10-24 17:53:07
【问题描述】:

我在想一个问题,如果hashcode函数为假但equal函数为真,会发生什么?例如:

public class Demo {

    private int age;

    private String name;

    //getter
    //setter

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Demo demo = (Demo) o;
        return age == demo.age &&
                Objects.equals(name, demo.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(age, name)
                + (new Random().nextInt(1000));
    }
}

【问题讨论】:

  • 哈希码不是假的,你只是对相等的对象有不同的哈希码。
  • 如果您尝试将这样的对象放入哈希集中,或者作为哈希映射中的键,容器将无法正常工作。
  • 没关系,除非你做的事情需要相等的对象具有相等的哈希值。例如,您是否尝试过将对象添加到 HashSet?

标签: java equals hashcode


【解决方案1】:

将会发生的情况是Demo 类的实例在用作哈希键时会出现错误行为。

下面是一个例子。

Demo demo = new Demo(...);
HashSet<Demo> set = new HashSet<>();
set.add(demo);
System.out.println(set.contains(demo));  // will print false 99.9% of the time.

换句话说,从contains 方法的角度来看,HashSet 将丢失轨道元素。 (但如果您迭代集合,它们仍然会存在。而且您可能能够添加相同的 Demo 对象两次...导致集合包含重复项。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 2012-09-22
    • 1970-01-01
    • 2013-04-01
    • 2012-05-10
    相关资源
    最近更新 更多