right way to incorporate superclass into a Guava Objects.hashcode() implementation?

前端 未结 3 1087
别跟我提以往
别跟我提以往 2021-02-12 10:44

Possibly a dumb question, but I don\'t want to screw this up. Let\'s say I have two Java classes, Class1 and Class2, where Class2 extends Class1

相关标签:
3条回答
  • 2021-02-12 11:15

    Although Bozho's suggestion is valid, I prefer this approach:

    @Override
    public int hashCode() {
        return Objects.hashcode(mField1, getParentField1(), getParentField2());
    }
    
    0 讨论(0)
  • 2021-02-12 11:23

    Yes, that looks correct. It would be the same if you had Objects.hashCode(f1, f2, f3, f4). If you look at the implementation, it's something like result += 31 * result + hashcodeOfCurrentObject. Which means that your result will be 31 + the super hashcode, which is not exactly the same, but would not be a problem.

    0 讨论(0)
  • 2021-02-12 11:25

    Effective Java does address this situation...by saying that you shouldn't do it. Item 8:

    It turns out that this is a fundamental problem of equivalence relations in object-oriented languages. There is no way to extend an instantiable class and add a value component while preserving the equals contract, unless you are willing to forgo the benefits of object-oriented abstraction.

    (Corollary: the same reasoning applies to hashCode().)

    0 讨论(0)
提交回复
热议问题