Partial ordered Comparator

后端 未结 6 1479
灰色年华
灰色年华 2020-12-18 22:35

How to implement java.util.Comparator that orders its elements according to a partial order relation?

For example given a partial order relation a

6条回答
  •  北海茫月
    2020-12-18 23:00

    Any time I've tried using hash codes for this sort of thing I've come to regret it. You will be much happier if your ordering is deterministic - for debuggability if nothing else. The following will achieve that, by creating a fresh index for any not previously encountered Item and using those indices for the comparison if all else fails.

    Note that the ordering still is not guaranteed to be transitive.

    class ItemPartialOrderComperator implements Comparator {
        @Override
        public int compare(Item o1, Item o2) {
            if(o1.equals(o2)) {
                return 0;
            }
            if(o1.before(o2)) {
                return -1;
            }
            if(o2.before(o1)) {
                return +1;
            }
            return getIndex(o1) - getIndex(o2);
        }
    
        private int getIndex(Item i) {
            Integer result = indexMap.get(i);
            if (result == null) {
                indexMap.put(i, result = indexMap.size());
            }
            return result;
        }
    
        private Map indexMap = new HashMap();
    }
    

提交回复
热议问题