Impose a total ordering on all instances of *any*

2019-07-04 06:12发布

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?

7条回答
爷的心禁止访问
2楼-- · 2019-07-04 06:43

I don't think it does since this clause is not met:

Finally, the implementer must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

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?

查看更多
登录 后发表回答