首页 > 解决方案 > 为什么 priorityQueue 不对元素进行排序

问题描述

我有下面的代码

        Comparator<StudentDTO> compareNames = Comparator.comparing(StudentDTO::getName);
    PriorityQueue<StudentDTO> h = new PriorityQueue<>(compareNames);

    h.offer(new StudentDTO(5, "c"));
    h.offer(new StudentDTO(2, "b"));
    h.offer(new StudentDTO(8, "z"));
    h.offer(new StudentDTO(1, "a"));

System.out.println(h);

我得到如下输出:

[StudentDTO [rollNo=1, Name=a], StudentDTO [rollNo=2, Name=b], StudentDTO [rollNo=8, Name=z], StudentDTO [rollNo=5, Name=c]]

不知道为什么 Name=z 出现在 Name=c 之前。编辑:我正在使用 java 8。

标签: javacollectionsqueuepriority-queue

解决方案


当您PriorityQueue像这样打印时 - 在下面调用toString方法 from 。AbstractCollection它使用Iterator扩展集合 - 在你的情况下- 遍历集合并从中PriorityQueue创建一个。String如果你检查它的文档,PriorityQueue::iterator它会返回迭代器,它以没有特定的顺序返回元素:

返回此队列中元素的迭代器。迭代器不会以任何特定顺序返回元素。

如果您想按比较器定义的优先级顺序检索元素,请使用 和 等poll方法remove。考虑到您已经覆盖StudentDTO::toString method了类似这样的内容,将从队列中打印对象,并将它们从队列中删除:

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

和输出:

StudentDTO{rollNo=1, name='a'}
StudentDTO{rollNo=2, name='b'}
StudentDTO{rollNo=5, name='c'}
StudentDTO{rollNo=8, name='z'}

推荐阅读