If I do the following
myObject.myMethod(myClass.getComparator());
with
public void myMethod(Comparator<? super myOtherObject> comparator) {
if (comparator.equals(myClass.getComparator()) {
//do sth
}
}
and in myClass
static Comparator<ListItem> getComparator() {
return new Comparator<myOtherObject>() {
public int compare(myOtherObjectitem1, myOtherObjectitem2) {
return (Integer.valueOf(myOtherObject.getRating()).compareTo(Integer.valueOf(myOtherObject.getRating())));
}
};
}
then “//do sth” is not gonna be executed. So the objects I get from getComparator the two times are different. How can that be? Is there a chance to see, which comparator “myMethod” gets?
You’re calling the
equalsmethod on this line:Since you haven’t defined this method explicitly on your Comparator class (which is an anonymous inner class), this defaults to the version inherited from
Object– which considers two references equal only if they are the exact same object.And your
getComparator()method statesreturn new Comparator() { ... }, so it’s calling the constructor and creating a new object each time it’s called. Thus the result of one call togetComparatorwill be a distinct object, and hence will not be considered equal to, the result of another call.I can think of two possible ways to change your code so that the equality test returns true:
Create the comparator only once, and return this same object from
getComparator. This would involve a change somewhat like thefollowing in
myClass:Provide an explicit
equals()implementation (and thus ahashCode()one too, ideally). You can then control exactly which objects are considered equal to one of your comparators. This might be much easier if you define a concrete class for your comparator rather than it being an anonymous inner class.At the end of the day, though, I fear your approach might not be right. What does it mean for two comparators to be equal to one another? I feel this is an ambiguous concept for anything other than data classes, and I would be hesitant to use the
Object.equalsmethod for this.(For example, if by equality you mean “they will sort lists in the same order”, then I’d add a method to your comparator class called
isEquivalentSortOrderor something similar. This way you can specify exactly what you mean without having to rely on the woolly definition of “being the same”.)