Search code examples
javaqueuepriority-queuecomparable

Maintain Entry Sequence in a PriorityQueue


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!


Solution

  • 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