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
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().
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 thatsgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2))
for every object referenceo1
ando2
.
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.