根据OP的评论 https://stackoverflow.com/questions/19182700/collections-sort-throws-comparison-method-violates-its-general-contract-excep?noredirect=1#comment28381311_19182700, 我的建议 https://stackoverflow.com/questions/19182700/collections-sort-throws-comparison-method-violates-its-general-contract-excep/19183199#comment28380870_19182700使用的
Double.compare(score, o.score)
解决了这个问题。我的猜测是有问题±0
s or NaN
s。事实上,如果你看看它的来源Double.compare()
,你会发现它比你想象的稍微复杂一些,并且专门处理这些情况:
958 public static int compare(double d1, double d2) {
959 if (d1 < d2)
960 return -1; // Neither val is NaN, thisVal is smaller
961 if (d1 > d2)
962 return 1; // Neither val is NaN, thisVal is larger
963
964 long thisBits = Double.doubleToLongBits(d1);
965 long anotherBits = Double.doubleToLongBits(d2);
966
967 return (thisBits == anotherBits ? 0 : // Values are equal
968 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
969 1)); // (0.0, -0.0) or (NaN, !NaN)
970 }
(source http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Double.java#Double.compare%28double,double%29)
寓意是:比较双精度数时要小心! :)
参考:
- Double.compare() http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare%28double,%20double%29