1

in java PMD rules, there is a rule OverrideBothEqualsAndHashcode.

it means that developer has to override both equals(Object obj) and hashCode() not just one.

can someone explain why?

and if i override and re-define eqauls(Object obj), what should i implement in hashCode() ?

class MyClass() {
    public int id;

    @Override
    public boolean equals(Object obj) {
        return id == ((MyClass) obj).id;
    }

    @Override
    public int hashCode() {
        // WHAT KIND OF CODE SHOULD I IMPLEMENT HERE?
    }
}
J.ty
  • 337
  • 1
  • 3
  • 18

1 Answers1

1

If you override equals, you must override hashCode, since the contract of hashCode requires that equal objects have the same hashCode.

As for the hashCode implementation of your particular example, that's simple. Since your equality is determined by a single int instance variable, hashCode should simply return that variable.

This gives you the best possible hashCode implementation - non equal MyClass instances will never have the same hashCode.

@Override
public int hashCode() {
    return id;
}
Eran
  • 387,369
  • 54
  • 702
  • 768