Your Comparator
是正确的。问题是您很可能使用其遍历列表Iterator
. The PriorityQueue文档 https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html状态:
方法 iterator() 中提供的迭代器不保证
以任意特定顺序遍历优先级队列的元素。
如果你要迭代你的PriorityQueue
像这样,您应该看到正确的结果:
while (!pq.isEmpty())
System.out.println(pq.poll().getName());
}
我在这个答案的末尾包含了一个示例来充分演示。
如果您不想清除您的数据,您可以执行以下操作:PriorityQueue
。就我个人而言,我不建议将这两种方法作为初始选择PriorityQueue
对于用例来说不正确,因为它们不打算被迭代。
你可以复制你的PriorityQueue
放入一个数组中,使用您的对它们进行排序Comparator
实现,迭代排序数组,例如:
Student[] students = pq.toArray(new Student[pq.size()]);
Arrays.sort(students, new StComp());
for (Student s : students) {
System.out.println(s.getName() + " " + s.getCgpa() + " " + s.getId());
}
或将它们添加到某种Collection
轮询时,然后将它们添加回PriorityQueue
, e.g.:
Collection<Student> temp = new LinkedList<>();
while (!pq.isEmpty()) {
Student s = pq.poll();
System.out.println(s.getName() + " " + s.getCgpa() + " " + s.getId());
temp.add(s);
}
pq.addAll(temp);
该示例使用您的数据来演示:
Main
public class Main {
public static void main(String[] args) {
PriorityQueue<Student> pq = new PriorityQueue<>(new StComp());
pq.add(new Student("John", 75, 50)); // Student name, grade average, id
pq.add(new Student("Mark", 8, 24));
pq.add(new Student("Shafaet", 7, 35));
pq.poll();
pq.poll();
pq.add(new Student("Samiha", 85, 36));
pq.poll();
pq.add(new Student("Ashley", 9, 42));
pq.add(new Student("Maria", 6, 46));
pq.add(new Student("Anik", 95, 49));
pq.add(new Student("Dan", 95, 50));
pq.poll();
// Not guaranteed to be in priorty order
System.out.println("Using PriorityQueue's Iterator, may not be in the correct priority order.");
for (Student s : pq) {
System.out.println(s.getName() + " " + s.getCgpa() + " " + s.getId());
}
// Correct order, but removes from the Priority Queue
System.out.println("\nIterating until empty using PriorityQueue.poll(), will be in the correct order.");
while (!pq.isEmpty()) {
Student s = pq.poll();
System.out.println(s.getName() + " " + s.getCgpa() + " " + s.getId());
}
}
}
Student(重命名,应该是单数)
public class Student {
private double cgpa;
private String name;
private int id;
public Student(String name, double cgpa, int id) {
this.name = name;
this.cgpa = cgpa;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public double getCgpa() {
return cgpa;
}
}
StComp(逻辑与问题相同)
public class StComp implements Comparator<Student> {
@Override
public int compare(Student st1, Student st2) {
if (st1.getCgpa() == st2.getCgpa()) {
if (st1.getName().equals(st2.getName())) {
return st1.getId() - st2.getId();
} else {
return st1.getName().compareTo(st2.getName());
}
} else {
return (st1.getCgpa() < st2.getCgpa()) ? 1 : -1;
}
}
}
Output(至少对我来说,第一次的结果可能会有所不同Iterator
变体)
Using PriorityQueue's Iterator, may not be in the correct priority order.
Dan 95.0 50
Ashley 9.0 42
Maria 6.0 46
Shafaet 7.0 35
Iterating until empty using PriorityQueue.poll(), will be in the correct order.
Dan 95.0 50
Ashley 9.0 42
Shafaet 7.0 35
Maria 6.0 46