0
votes

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!

1
Priority queues don't preserve order the way a normal LIFO queue would: en.wikipedia.org/wiki/Priority_queue - rtperson
If you need to maintain entry-sequence (or any sequence other than priority), do not use a PQ. The answer to the riddle: The PQ probably uses a Tree (Binary Heap) structure. - Henk Holterman
But there is no ordinary Queue in Java that I can use. What else can I use to maintain the entry sequence? - Carven

1 Answers

7
votes

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