问题
I'm currently studying the Comparator
interface and noticed that in the documentation for Comparator's equals method, it states
Note that it is always safe not to override Object.equals(Object)
I have checked the implementation for the default equals
method in Object
class
So with the default implementation of equals
method, it simply checks whether two instances points to the same object because this == obj
tests for reference equality.
But what happen if I have two instances of Comparator
, the result they return are identical, and I want to know if they are equivalent. If I dont override the default Object's equals
method, then regardless of whether the result they return is equivalent or not, by using the default Object's equals
method, false
will always be returned. So is it still always safe not to override the Object.equals(Object)?
回答1:
I suppose you mis-interpreted what java doc is saying:
this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator
Default implementation will return true only if it is exactly the same object, which by definition means that they both (actually single one) provide the same sorting order
This definition does not imply that it will return true for different comparators even if they provide the same sorting order, simple verification:
import java.util.Comparator;
public class TestComparator {
static class Comparator1 implements Comparator<Integer> {
@Override
public int compare(final Integer o1, final Integer o2) {
return Integer.compare(o1, o2);
}
}
static class Comparator2 implements Comparator<Integer> {
@Override
public int compare(final Integer o1, final Integer o2) {
return Integer.compare(o1, o2);
}
}
public static void main(final String[] args) {
final Comparator1 c1 = new Comparator1();
final Comparator1 c11 = new Comparator1();
final Comparator2 c2 = new Comparator2();
System.out.println(c1.equals(c1)); // true
System.out.println(c1.equals(c11)); // false
System.out.println(c1.equals(c2)); // false
}
}
Default implementation can return true if comparators equivalent, also it can return false (if objects are different)
Note further, doc says:
However, overriding this method may, in some cases, improve performance by allowing programs to determine that two distinct comparators impose the same order.
So, it is safe not to override, but it is not enough to guarantee that different but equivalent comparators will be compared properly
来源:https://stackoverflow.com/questions/49786873/comparator-interfaces-equals-method-why-it-is-always-safe-not-to-override-obje