Hashcode and equals

后端 未结 7 2420
死守一世寂寞
死守一世寂寞 2020-11-30 14:00

equals and hashCode method must be consistent, which means that when two objects are equal according to equals method their hash

7条回答
  •  攒了一身酷
    2020-11-30 14:52

    Equality is only determined by method equals(). And method hashCode() is used in other situations, like by Map or Set. It is somewhat like a pre-condition or hint before actually calling equals (for efficiency). So it is assumed that if 2 objects are equal (that is, equals() returns true), then their hashCodes() must return the same value.

    So in your code, 2 objects are equal, as long as your overriden equals() returns true, no matter what hashCode() does. hashCode() is not called at all when comparing for equality.

    This question has more in-depth information regarding to the relationship between equals() and hashCode().

提交回复
热议问题