这个比较器方法有什么问题?
我读过: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;
}
}发布于 2019-05-01 23:35:53
我认为您的问题出在您的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;
}https://stackoverflow.com/questions/55938101
复制相似问题