Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of equals() method in comparator interface?

Tags:

java

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?

like image 676
nit Avatar asked Feb 29 '12 11:02

nit


3 Answers

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 that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.

The method can be used to establish whether or not two distinct comparators impose the same order.

like image 154
NPE Avatar answered Nov 18 '22 11:11

NPE


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.

like image 39
Stephen C Avatar answered Nov 18 '22 10:11

Stephen C


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.

like image 4
dee-see Avatar answered Nov 18 '22 10:11

dee-see