在java中,双精度数据类型在优先级队列中排序不正确

在java中,双精度数据类型在优先级队列中排序不正确,java,Java,我使用优先级队列根据cgpa对学生列表进行排序,cgpa是一个双值。若我将它设置为整数,那个么它运行良好,或者若我将一个字段名添加为string,并根据string进行排序,那个么它也运行良好 public class MainClass { public static void main(String[] args) { // comparator class to sort the student on basis of cgpa. Compar

我使用优先级队列根据cgpa对学生列表进行排序,cgpa是一个双值。若我将它设置为整数,那个么它运行良好,或者若我将一个字段名添加为string,并根据string进行排序,那个么它也运行良好

    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());
        }
    }
    }
这是我的意见

3.75
3.8
3.7
3.85
3.9
3.6
3.95
3.95
这是输出

3.95
3.95
3.9
3.85
3.8
3.6
3.7
3.75

我尝试了strictfp关键字并尝试使用双包装器类,但仍然存在相同的问题。

您的代码看起来不错,甚至迭代优先级队列的代码都是正确的,但它并没有提供有序遍历。原因是
PriorityQueue
的内部工作方式使得迭代器无法保证特定的顺序

正如报告所讨论的:

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

使用数组.sort(studentList.toArray()):


同意上述答案。但我想补充一点,没有理由对PriorityQueue排序。您可以使用poll方法。而(!studentList.isEmpty())System.out.println(studentList.poll().getCgpa());谢谢你的建议。我从优先级队列中轮询数据,而不是为每个队列轮询数据,结果成功了。我要纠正的一件事是,我不能使用Arrays.sort()对数组进行排序,因为我的学生类没有实现可比较的接口,所以我将得到一个异常,并且优先级队列已经对数据进行了排序。@如果您同意从队列中删除元素,Ishan轮询在这里似乎是一个非常聪明的选择。如果您想保持队列的完整性,这不是一个选项。是的,您是对的,在这方面,我应该使用comparable而不是comparator,并且可以使用array.sort()。我刚才试过了,也成功了。
3.95
3.95
3.9
3.85
3.8
3.6
3.7
3.75
Student[] students = Arrays.sort(studentList.toArray());

for (Student s : students) {
    System.out.println(s.getCgpa());
}