java 关于Comparable [已关闭]

fv2wmkja  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(99)

已关闭,此问题需要更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);
    }

如果有人知道为什么会这样,请告诉我

v6ylcynt

v6ylcynt1#

这些是Double的比较方法

public int compareTo(Double anotherDouble) {
    return Double.compare(value, anotherDouble.value);
}

public static int compare(double d1, double d2) {
    if (d1 < d2)
        return -1;           // Neither val is NaN, thisVal is smaller
    if (d1 > d2)
        return 1;            // Neither val is NaN, thisVal is larger

    // Cannot use doubleToRawLongBits because of possibility of NaNs.
    long thisBits    = Double.doubleToLongBits(d1);
    long anotherBits = Double.doubleToLongBits(d2);

    return (thisBits == anotherBits ?  0 : // Values are equal
            (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
             1));                          // (0.0, -0.0) or (NaN, !NaN)
}

它返回0、-1或1。
如果你改变参数,结果就会反转。如果是相等的,你不会注意到有什么不同。

8yoxcaq7

8yoxcaq72#

我试过你的密码,

public int compareTo(@NotNull Student o) {
    System.out.println("o.score: " + o.score);
    System.out.println("this.score: " + this.score);
    int i = Double.valueOf(this.score).compareTo(o.score);
    System.out.println(i);
    return i;
}

public static void main(String[] args) {
    List<Student> students = Stream.of(
            new Student("A", 100d),
            new Student("B", 200d),
            new Student("C", 300d)
    ).collect(Collectors.toList());

    Collections.sort(students);
    students.forEach(System.out::println);
}

结果

o.score: 100.0
this.score: 200.0
1
o.score: 200.0
this.score: 300.0
1
Student{name='A', score=100.0}
Student{name='B', score=200.0}
Student{name='C', score=300.0}

通过这样,

int i = Double.valueOf(o.score).compareTo(this.score);

结果,

o.score: 100.0
this.score: 200.0
-1
o.score: 200.0
this.score: 300.0
-1
Student{name='C', score=300.0}
Student{name='B', score=200.0}
Student{name='A', score=100.0}

在我看来,正确的应该是

Double.valueOf(this.score).compareTo(o.score);

因为compareTo的用法应该是这个双精度compareToanotherDouble,其中anotherDouble是参数。如果你这样做

Double.valueOf(o.score).compareTo(this.score);

该参数与从Comparable实现的compareTo方法中的参数相反

相关问题