equals()
method is available to all java collection classes from the Object
class. This method is also declared in Comparator
interface, so what is the purpose of declaring this method in Comparator? in which case is it used and how?
what is the purpose of declaring this method in Comparator?
I think it's the designer's way of highlighting the fact that Comparator.equals()
imposes some additional requirements on any classes that implement the interface:
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
.
The method can be used to establish whether or not two distinct comparators impose the same order.
I think that the main reason is to make it clear that equals
method is for testing the Comparator
itself. This is obvious when you think about it, but can I imagine that some people might expect equals(Object)
to (somehow) be semantically related to the compare(T, T)
method.
It also allows the documentation of some common-sense guidelines for when two comparators could be viewed as equal.
Either way, the presence of the equals(Object)
method in the interface is solely for documentation purposes.
From the javadoc
Note that it is always safe not to override Object.equals(Object). However, overriding this method may, in some cases, improve performance by allowing programs to determine that two distinct comparators impose the same order.
The idea is simply to be able to allow you to not sort a collection that has already been sorted by another comparator if you realize that the end result will be the same.
Generally it had little use, but when sorting very large collections it is something you might want to look into.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With