如何实现java.util.Comparator根据偏序关系对其元素进行排序?
例如,给定的部分顺序关系一个 ≺ Ç,b ≺ Ç ; a和b的顺序是不确定的.
由于Comparator需要总排序,因此实现命令部分排序未定义但是一致的元素.
以下工作会怎样?
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
}
}
Run Code Online (Sandbox Code Playgroud)