double数据类型在java中的优先级队列中没有正确排序

Ish*_*han 3 java

我正在使用优先级队列来根据cgpa对学生列表进行排序,这是一个双倍值.如果我将它作为整数而不是它正常工作或者如果我将字段名称添加为字符串并基于字符串排序那么它也可以正常工作.

    public class MainClass {


    public static void main(String[] args) {

    // comparator class to sort the student on basis of cgpa.
        Comparator<Student> studentComparator = new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                if (s1.getCgpa() < s2.getCgpa())
                    return 1;
                else if (s1.getCgpa() > s2.getCgpa())
                    return -1;
                else
                    return 0;
            }
        };

        Scanner in = new Scanner(System.in);
        int totalEvents = 8;
        PriorityQueue<Student> studentList = new PriorityQueue<>(totalEvents, studentComparator);
       // adding value in to priority queue by taking input from user in cmd
        while(totalEvents>0) {
            double cgpa = in.nextDouble();
            Student student = new Student(cgpa);
            studentList.add(student);
            totalEvents--;
        }

        for (Student s : studentList) {
            System.out.println(s.getCgpa());
        }
    }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的模特课.

    class Student {

    private double cgpa;

    public Student(double cgpa) {
        super();
        this.cgpa = cgpa;
    }

    public double getCgpa() {
        return cgpa;
    }

 }
Run Code Online (Sandbox Code Playgroud)

这是我的意见

3.75
3.8
3.7
3.85
3.9
3.6
3.95
3.95
Run Code Online (Sandbox Code Playgroud)

这是输出

3.95
3.95
3.9
3.85
3.8
3.6
3.7
3.75
Run Code Online (Sandbox Code Playgroud)

我尝试了strictfp关键字并试图使用Double包装类,但仍然是同样的问题.

Tim*_*sen 7

您的代码看起来很好,甚至您的代码来迭代优先级队列是正确的,但它没有给您一个有序的遍历.其原因是内部工作原理PriorityQueue使得迭代器无法保证特定的顺序.

正如PriorityQueueJavadoc讨论:

方法iterator()中提供的迭代器不保证以任何特定顺序遍历优先级队列的元素.如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray()).

用途Arrays.sort(studentList.toArray()):

Student[] students = Arrays.sort(studentList.toArray());

for (Student s : students) {
    System.out.println(s.getCgpa());
}
Run Code Online (Sandbox Code Playgroud)

  • 同意以上答案.但我想补充一点,没有理由对PriorityQueue进行排序.您可以使用poll方法.while(!studentList.isEmpty())System.out.println(studentList.poll().getCgpa()); (3认同)