Why does Comparator declare equals?

后端 未结 8 1534
无人及你
无人及你 2021-02-05 04:34

The Comparator interface has its own equals() method. Any class will get equals() by default through Object class. What is the need to have equal

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 04:49

    Comparator refines the contract of Object.equals: It has to satisfy the constraints set out by Object.equals and then some.

    Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator. Thus, comp1.equals(comp2) implies that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.

    Declaring an equals inside Comparator allows you to document this in the form of javadoc.

    Note that the documentation of the API also serves as the contract, so it's not just cosmetics here. It's explicit constraints that other code and your code can rely on.

    In similar situations where you have less established methods, it may also serve as documenting an intent. I.e., Interface.method should be there, regardless of how its super interfaces evolves.

提交回复
热议问题