有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过equals和hashcode区分子类

我正在寻找关于在子类中重写hashcode和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. 同名的FruitVegetable不应该相等

问题:

  1. 您希望子类equals只包含子类的instanceof检查和对super.equals的调用吗
  2. 为了让同名的FruitVegetable实例具有不同的哈希代码,应该如何构造哈希代码

共 (1) 个答案

  1. # 1 楼答案

    1. Would you expect the equals to simply contain an instanceof check and a call to super.equals?

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

    someFruit.equals(someFood) // will be false
    someFood.equals(someFruit) // will be true
    
    <>这可能不是一个EME>问题,但这是一件你应该考虑的事情。p>

    如果你不想破坏合同,在这种情况下Food应该检查this.getClass() == obj.getClass()。如果你这样做了,那么你也不一定需要在子类中重写它

    否则就无关紧要了。该方法是按合同定义的,您可以按照自己的意愿实现它

    1. How should the hashcode be structured in an attempt to have Fruit and Vegetable instances with the same name have different hashcodes?

    他们不需要与众不同