English 中文(简体)
在优先级队列中维护条目序列
原标题:Maintain Entry Sequence in a 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,然后只返回0覆盖copmareTo(obj)方法。

但奇怪的是这里。当我。。。

queue.poll();  //return: pet1  queue: pet3, pet2
queue.poll();  //return: pet3  queue: pet2

既然我已经按pet1、pet2和pet3的顺序添加了它们,为什么在我第一次调用poll()时,它会对我的宠物序列进行排序?然后这整件事就不再是一个队列了,因为它的入口序列没有被保留,不是吗?

我怀疑这可能与Comparable接口和compareTo(obj)方法有关。但我所需要的只是保持它的输入顺序,所以我根本不需要比较任何东西或排序任何东西。

如何在队列中维护其条目顺序?

谢谢

最佳回答

为了保存序列,您必须使用正常的队列

您必须创建一个类似LinkedList从队列实现链表

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签