Best practice to choose fields for equals() implementation

前端 未结 5 1969
栀梦
栀梦 2021-02-05 13:43

When writing unit-tests, I often face the situation when equals() for some object in tests -- in assertEquals -- should work differently from how it wo

5条回答
  •  执念已碎
    2021-02-05 14:14

    I think the only best practice when overriding the equals() method is common sense.

    There are no rules, apart from the equivalence definition of the Java API. Once you've chosen that definition of the equality, you have to apply it to your hashCode() method as well.

    By that I mean, as a developer, you, your co-workers and maintainers should know when your instance of let's say a Watermelon equals another Object instance.

提交回复
热议问题