priorityqueue使用类oops样式的比较器

vdgimpew  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(240)

这个问题在这里已经有答案了

priorityqueue.tostring元素顺序错误(4个答案)
优先级队列未维护排序顺序(3个答案)
为什么priorityqueue中的元素没有按其自然顺序打印[重复](1个答案)
java:priorityqueue从自定义比较器返回错误的顺序[重复](2个答案)
13小时前关门了。
我有一个班叫学生

public class Student {
    private Long ID;
    private String Name;
    private Float CGPA;

    public Student(Long ID, String Name, Float CGPA) {
        this.ID = ID;
        this.Name = Name;
        this.CGPA = CGPA;
    }

    public Long getID() {
        return this.ID;
    }

    public Float getCGPA() {
        return this.CGPA;
    }

    public String getName() {
        return this.Name;
    }
}

下面是创建优先级队列的代码

@Test
    void testQueue() {
        List<Student> students = new ArrayList<>();

        students.add(new Student(50L, "John", 3.75f));
        students.add(new Student(24L, "Mark", 3.8f));
        students.add(new Student(49L, "Anik", 3.95f));
        students.add(new Student(51L, "Dan", 3.95f));
        students.add(new Student(42L, "Ashley", 3.9f));
        students.add(new Student(50L, "Dan", 3.95f));
        students.add(new Student(46L, "Maria", 3.6f));
        students.add(new Student(35L, "Shafaet", 3.7f));
        students.add(new Student(36L, "Samiha", 3.85f));

        Comparator<Student> studentComparator = Comparator
                .comparingDouble(Student::getCGPA).reversed();
        PriorityQueue<Student> pq = new PriorityQueue<>(studentComparator);
        pq.addAll(students);
        for (Student student : pq) {
            System.out.print(student.getName() + "," + student.getCGPA() + "," + student.getID() + "\n");
        }
    }

我得到这个输出:

Anik,3.95,49
Dan,3.95,51
Dan,3.95,50
Samiha,3.85,36
Ashley,3.9,42
Mark,3.8,24
Maria,3.6,46
Shafaet,3.7,35
John,3.75,50

正如你所看到的,我的比较仪清楚地使用 Student::getCGPAreversed() 尽管阿什利得到了大于3.85的3.9,但阿什利还是在萨米哈之后得到了印刷品。前3个是正确的,3.95是最高的。
为什么比较器不能正常工作?有什么想法吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题