Java 比较器未按预期工作的优先级队列

Java 比较器未按预期工作的优先级队列,java,priority-queue,Java,Priority Queue,优先级队列未按照比较器的顺序工作 输出: [Tim,5],[Joe,12],[Alice,7] 预期: [Tim,5],[Alice,7],[Joe,12] 有谁能帮我解释一下比较器没有给出预期输出的原因。来自: 方法PriorityQueue.Iterator()中提供的迭代器不可用 保证以任何方式遍历优先级队列的元素 特定顺序。如果需要有序遍历,请考虑使用 Arrays.sort(pq.toArray()) PriorityQueue是一个队列,它不会对值进行动态排序。您需要使用Prior

优先级队列未按照比较器的顺序工作

输出: [Tim,5],[Joe,12],[Alice,7]

预期: [Tim,5],[Alice,7],[Joe,12]

有谁能帮我解释一下比较器没有给出预期输出的原因。

来自:

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


PriorityQueue是一个队列,它不会对值进行动态排序。您需要使用PriorityQueue.poll方法来按顺序获取对象

static class Student {
    String name;
    int roll;

    public Student(String name, int roll) {
        this.name = name;
        this.roll = roll;
    }

    @Override
    public String toString() {
        return "["+ name +","+roll+"]";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getRoll() {
        return roll;
    }

    public void setRoll(int roll) {
        this.roll = roll;
    }
}

public static void main(String[] args) {

    Comparator<Student> byRoll = Comparator.comparing(Student::getRoll);

    PriorityQueue<Student> pq = new PriorityQueue<>(byRoll);

    pq.add(new Student("Tim", 5));
    pq.add(new Student("Joe", 12));
    pq.add(new Student("Alice", 7));

    while(!pq.isEmpty()) {
        System.out.println( pq.poll().toString());
    }

}
静态类学生{
字符串名;
整流罩;
公立学生(字符串名称,整数卷){
this.name=名称;
this.roll=roll;
}
@凌驾
公共字符串toString(){
返回“[”+名称+”,“+滚动+”];
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共int getRoll(){
回程辊;
}
公共无效设置卷(整数卷){
this.roll=roll;
}
}
公共静态void main(字符串[]args){
比较器byRoll=比较器。比较(Student::getRoll);
PriorityQueue pq=新的PriorityQueue(byRoll);
pq.添加(新学生(“Tim”,5));
pq.add(新学生(“Joe”,12));
pq.add(新学生(“Alice”,7));
而(!pq.isEmpty()){
System.out.println(pq.poll().toString());
}
}

您的代码非常好,无需更改比较器或数组。排序或添加getter/setter等。 只需更改您的打印声明,如下所示:

while(!pq.isEmpty()) {
        System.out.println(pq.poll().toString());
    }

希望这有帮助。

优先级队列的迭代器
“不以任何特定顺序返回元素”寻求调试帮助的问题必须包括所需的行为、特定的问题或错误,以及在问题本身中重现这些问题所需的最短代码。看见