java - 为什么 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。
解决方案
当您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'}
推荐阅读
- swift - 为什么我会在这里丢失数据?(SwiftUI)
- java - @RequestMapping 的问题
- javascript - this.activatedRoute.queryParamMap.pipe 中的单元测试茉莉花错误
- go - 如何在go html模板中连接href
- java - AWS ECS 中的 Java 服务抛出 java.io.IOException:打开的文件过多
- javascript - 如何从 node.js 服务器下载目录
- slick.js - 控制带有垂直页面滚动的粘性 Slick Slider
- sox - 结合2个不同文件的不同通道
- android - 领域:安卓 | Java : 请为此领域文件输入有效的加密密钥
- c# - 使用 WebClient 或 HttpClient 将文件分多个部分上传到 Amazon S3