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

僤鯓⒐⒋嵵緔 提交于 2019-12-03 07:14:08

问题


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

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

But then this gives no probs compilating:

 Comparator a = new Comparator() {      
     @Override public int compare(Object o1, Object o2) {
        //..
     }
 };

But this does:

 Comparator a = new Comparator() {      
     @Override public boolean equals(Object comparator) {
        //..
     }
 };

How its done for the interface for allowing us not to override method?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/11758006/why-is-equals-not-mandatory-to-implement-in-java-util-comparator

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