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

假装没事ソ 提交于 2019-12-02 20:47:20

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.

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!