【问题标题】:Distinguish between subclasses via equals & hashcode通过 equals 和 hashcode 区分子类
【发布时间】:2014-03-17 06:17:40
【问题描述】:

我正在寻找有关在子类中同时覆盖哈希码和 equals 的指导。

我在这里发现了一个类似的问题:Overriding equals() & hashCode() in sub classes ... considering super fields

但我想要的是稍微不同的东西。

想象一下这个(有点愚蠢的)例子:

class Food {

  String name;

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Food) {
      Food other = (Food)obj;
      return name.equals(other.name);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return name.hashCode();
  }
}

class Vegetable extends Food {
  // No additional fields here
  // Some methods here
}

class Fruit extends Food {
  // No additional fields here
  // Some methods here
}

鉴于:

  1. 子类不添加任何额外字段
    • 至少在这个例子中,它们基本上只是标记类
  2. Fruit 和 Vegetable 同名,不应该相等

问题:

  1. 您是否希望子类 equals 仅包含对子类的 instanceof 检查和对 super.equals 的调用?
  2. 应该如何构造哈希码以使 Fruit 和 Vegetable 同名的实例具有不同的哈希码?

【问题讨论】:

  • 您可以使用类名作为哈希码的组成部分(例如:17*classname.hashcode() + super.hashcode())
  • 请注意,Java API 中的许多数据结构都显示了您在此处显示的行为。看看各种地图。例如,HashMap 可以等于 LinkedHashMap。地图会检查地图的内容。实现类并不重要。

标签: java equals hashcode


【解决方案1】:

您可以在Foo 的.equals() 中使用.getClass():

@Override
public final boolean equals(final Object obj)
{
    if (obj == null)
        return false;
    if (this == obj)
        return true;
    // Class<?> are signletons, therefore we can use ==/!=
    if (getClass() != obj.getClass())
        return false;
    return name.equals(((Foo) obj).name);
}

.getClass()将返回对象的类,因此Fruit或Vegetable,甚至Food。

对于.hashCode(),name.hashCode() 很好。不要忘记,不是.equals() 的两个对象的hashcode 没有要求是不同的。但如果你愿意,这里也可以使用.getClass():

@Override
public final int hashCode()
{
    return 31 * getClass().hashCode() + name.hashCode();
}

【讨论】:

  • 是的,看起来很公平,只是我试图表现得很好,并试图坚持 Josh Bloch 的“当你覆盖 equals 时总是覆盖 hashCode”的想法
  • 你确实覆盖了 hashCode。同样,没有要求如果 !o1.equals(o2) 则 o1.hashCode() != o2.hashCode()。或者,也许你误解了“你不在乎”的部分。我的意思是“这没关系”:=)
  • 请注意,这是一个合法的 hashCode() 实现,虽然没什么用:return 42;
【解决方案2】:
  1. 您是否希望 equals 仅包含一个 instanceof 检查和对 super.equals 的调用?

instanceof 在这里很危险,因为Food 不是抽象的。这意味着equals 不是对称的。

someFruit.equals(someFood) // will be false
someFood.equals(someFruit) // will be true

这可能不会变成问题,但这是你应该考虑的事情。

如果你不想违约,这是Food应该检查this.getClass() == obj.getClass()的情况。如果你这样做了,那么你也不一定需要在子类中覆盖它。

否则就无所谓了。该方法是根据合同定义的,您可以根据需要实现它。

  1. 应如何构造哈希码以使同名水果和蔬菜实例具有不同的哈希码?

它们不需要不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多