Why is equals not mandatory to implement in java.util.Comparator?

后端 未结 2 1625
醉梦人生
醉梦人生 2021-02-02 16:04

Either in Javadoc as well as the code itself, Comparator interface defines:

 int compare(T o1, T o2);
 boolean equals(Object obj);

But then thi

相关标签:
2条回答
  • 2021-02-02 16:45

    Beczuse every object already implements equals().

    In reality specifying equals() again in the Comparator interface definition accomplishes precisely nothing except giving a chance to document the contract and its relationship with compareTo().

    0 讨论(0)
  • 2021-02-02 16:50

    First of all JavaDocs explain clearly that you should implements this method:

    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.

    But later:

    Note that it is always safe not to override Object.equals(Object).

    How is it possible not to override equals(), even though it is part of an interface? Because this method is already implemented for each and every object in Java (in Object class).

    The declaration in the interface is there only to emphasise the importance of equals() with regards to Comparator by adding extra JavaDoc explanation.

    BTW if your comparator is stateless you should have only one instance of it - in which case the default equal() implementation is just fine.

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