维护 PriorityQueue 中的条目顺序
我正在尝试使用 Java 中的 PriorityQueue。
我有一些自定义对象,并以这种方式将它们添加到队列中:
Pet pet1 = new Pet();
Pet pet2 = new Pet();
Pet pet3 = new Pet();
PriorityQueue<Pet> queue = new PriorityQueue<Pet>();
queue.offer(pet1);
queue.offer(pet2);
queue.offer(pet3);
此时,我意识到我的 Pet 对象必须实现 Comparable,以免从 PriorityQueue 获取 ClassCastException。所以我让我的 Pet 实现了 Comparable,然后重写了 copmareTo(obj) 方法,只返回 0。
但奇怪的是这里。当我...
queue.poll(); //return: pet1 queue: pet3, pet2
queue.poll(); //return: pet3 queue: pet2
既然我已经按照 pet1、pet2 和 pet3 的顺序添加了它们,为什么在我第一次调用 poll() 时,它会对我的 pet 序列进行排序?那么这整个事情就不再是一个队列了,因为它的进入顺序没有被保留,不是吗?
我怀疑这可能与 Comparable 接口和compareTo(obj) 方法有关。但我所需要的只是让它保持其输入顺序,因此我实际上不需要比较任何内容或对任何内容进行排序。
如何维护其在队列中的进入顺序?
谢谢!
I am trying to make use of the PriorityQueue in Java.
I have a few custom objects and I add them into the queue this way:
Pet pet1 = new Pet();
Pet pet2 = new Pet();
Pet pet3 = new Pet();
PriorityQueue<Pet> queue = new PriorityQueue<Pet>();
queue.offer(pet1);
queue.offer(pet2);
queue.offer(pet3);
At this point, I realise that my Pet objects must implement Comparable in order not to get ClassCastException from PriorityQueue. So I had my Pet implements Comparable, and then override the copmareTo(obj) method with just return 0.
But the weird thing is this here. When I...
queue.poll(); //return: pet1 queue: pet3, pet2
queue.poll(); //return: pet3 queue: pet2
Since I had added them in the order of pet1, pet2 and pet3, why on my first call to poll(), it sorted my pet sequences? Then this whole thing becomes no longer a queue anymore since its entry sequence isn't preserved, isn't it?
I suspect it may have to do with the Comparable interface and compareTo(obj) method. But all I needed is for it to maintain its entry sequence, so I don't really need to compare anything or sort anything at all.
How can I maintain its entry sequence in the queue?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了保护序列,您必须使用普通的 队列。
您必须创建一个类似 的实例LinkedList链表从Queue实现
In order to Preserver Sequence you have to use a normal Queue.
you will have to create an instance of something like a LinkedList linked list implements from Queue