我正在使用优先队列根据 cgpa 对学生列表进行排序,这是一个 double 值。如果我将它作为整数而不是工作正常,或者如果我将字段名称添加为字符串并根据字符串排序,那么它也可以正常工作。
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());
}
}
}
这是我的模型类。
class Student {
private double cgpa;
public Student(double cgpa) {
super();
this.cgpa = cgpa;
}
public double getCgpa() {
return cgpa;
}
}
这是我的意见
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 关键字并尝试使用 Double wrapper 类,但仍然是同样的问题。
最佳答案
你的代码看起来不错,甚至你迭代优先级队列的代码都是正确的,但它并没有给你一个有序的遍历。原因是 PriorityQueue
的内部工作方式使得迭代器无法保证特定顺序。
作为Javadoc for PriorityQueue讨论:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
使用Arrays.sort(studentList.toArray())
:
Student[] students = Arrays.sort(studentList.toArray());
for (Student s : students) {
System.out.println(s.getCgpa());
}
关于java - 双数据类型在 Java 的优先级队列中排序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41803351/