I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc.
class TotalOrder<T> implements Comparator<T> {
public boolean compare(T o1, T o2) {
if (o1 == o2 || equal(o1, o2)) return 0;
int h1 = System.identityHashCode(o1);
int h2 = System.identityHashCode(o2);
if (h1 != h2) {
return h1 < h2 ? -1 : 1;
}
// equals returned false but identity hash code was same, assume o1 == o2
return 0;
}
boolean equal(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
}
Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable?
I don't think it does since this clause is not met:
Since equal(o1, o2) depends on o1's implementation of equals, two objects that are logically equal (as determined by equals) still have two differrent identityHashCodes.
So when comparing them to a third object (z), they might end up yielding different values for compareTo.
Make sense?