【问题标题】:Priority Queue with Comparator not working as expected具有比较器的优先级队列未按预期工作
【发布时间】:2018-01-09 15:13:02
【问题描述】:

优先队列没有按照比较器的顺序工作。

See code snippet

输出: [蒂姆,5 岁],[乔,12 岁],[爱丽丝,7 岁]

预期: [蒂姆,5 岁],[爱丽丝,7 岁],[乔,12 岁]

谁能帮助我为什么比较器没有给出预期的输出。

【问题讨论】:

  • PriorityQueue的迭代器“不按任何特定顺序返回元素”
  • 寻求调试帮助的问题必须包含所需的行为、特定问题或错误,以及在问题本身中重现它所需的最短代码。见What topics can I ask about here?

标签: java priority-queue


【解决方案1】:

来自Java docs:

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

【讨论】:

    【解决方案2】:

    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());
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      您的代码非常好,无需更改 Comparator 或 Array.sort 或添加 getter/setter 等。 只需将您的打印声明更改如下:

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

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2021-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多