已关闭,此问题需要更focused,目前不接受回答。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。
2天前关闭。
Improve this question
我最近了解了comparable的概念,我正在编写一个代码来按双score值对Students(对象)进行排序。我知道如何对它们进行排序,但不知道升序和降序背后的逻辑。我将分享我编写的两个版本的代码(在实现Comparable<Student>
的student类中)
//This sorts the students in descending order
@Override
public int compareTo(Student o) {
return Double.valueOf(o.score).compareTo(this.score);
}
//This sorts the students in ascending order
@Override
public int compareTo(Student o) {
return Double.valueOf(this.score).compareTo(o.score);
}
如果有人知道为什么会这样,请告诉我
2条答案
按热度按时间v6ylcynt1#
这些是Double的比较方法
它返回0、-1或1。
如果你改变参数,结果就会反转。如果是相等的,你不会注意到有什么不同。
8yoxcaq72#
我试过你的密码,
结果
通过这样,
结果,
在我看来,正确的应该是
因为compareTo的用法应该是这个双精度compareToanotherDouble,其中anotherDouble是参数。如果你这样做
该参数与从
Comparable
实现的compareTo
方法中的参数相反