此比较器方法有什么问题?

我读过了 :
Java error: Comparison method violates its general contract

并了解如果c1> c2,并且c2> c3,则c1> c3。我相信以上情况也应如此。

getMaxCosine()返回0..1之间的值,第二种排序是根据卡中文本的长度,排名越高的时间越长。

public int compare(Card c1, Card c2) {
   if (getMaxCosine(c1) > getMaxCosine(c2)) {
       return -1;
   } else if (getMaxCosine(c1) == getMaxCosine(c2)) {
       return getMatchingText(c1).length() >= getMatchingText(c2).length() ? -1 : 1;
   } else {
       return 1;
   }
}

最佳答案

我认为您的问题出在您的if-else块中:

else if (getMaxCosine(c1) == getMaxCosine(c2)) {
       return getMatchingText(c1).length() >= getMatchingText(c2).length() ? -1  : 1;
}


如果getMatchingText(c1).length()等于getMatchingText(c2).length(),则返回-1。这将产生“不稳定”排序:换句话说,两个具有相等值的对象在排序后的顺序将相反。此外,对于在此比较器下相等的Card,您应该返回0。我建议在此>=->块中将if比较更改为else

else if (getMaxCosine(c1) == getMaxCosine(c2)) {
       if (getMatchingText(c1).length() == getMatchingText(c2).length()) return 0;
       return getMatchingText(c1).length() > getMatchingText(c2).length() ? -1  : 1;
}

关于java - 违反TimSort,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55938101/

10-13 04:37