Java – partially ordered comparator

How to implement Java. Net that sorts its elements according to the partial order relationship util. Comparator?

For example, given the partial order relationship a ≺ C, B ≺ C; The order of a and B is undefined

Because the comparator requires a complete sort, the elements that perform a partial sort are arbitrary but consistent

The following work?

interface Item {
    boolean before(Item other);
}

class ItemPartialOrderComperator implements Comparator<Item> {
    @Override
    public int compare(Item o1,Item o2) {
        if(o1.equals(o2)) {  // Comparator returns 0 if and only if o1 and o2 are equal;
            return 0;
        }
        if(o1.before(o2)) {
            return -1;
        }
        if(o2.before(o1)) {
            return +1;
        }
        return o1.hashCode() - o2.hashCode(); // Arbitrary order on hashcode
    }
}

Is the order for this comparator delivered? (I'm afraid it's not) does the comparator need to pass? (when used in treemap) > how to implement it correctly? (if the above implementation does not work) (hashcodes may conflict. In order to simplify the conflict, the example ignores the conflict; for fail safe sorting of hash codes, see Damien B's answer to impress a total ordering on all instances of * any * class in Java)

Solution

The problem is that when you have unparalleled elements, you need to be clearer than comparing hash codes For example, given partial order {a < B, C < D}, the hash code can satisfy H (d) H (b) H (c) H (a), which means that B < C < d < a (BOLD indicates the connection disconnected by the hash code), which will lead to the problem of treemap In general, you may not have anything to do except topological classification of keys in advance, so you are welcome to learn more about some orders you are interested in

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>