0

这种比较器方法有什么问题?

我已阅读: Java 错误:比较方法违反其一般合同

并且理解如果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;
   }
}
4

1 回答 1

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此外,对于在此比较器下相等的 s,您应该返回 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;
}
于 2019-05-01T15:35:52.717 回答