I use the priority queue to sort and use a large number of user objects. Objects have a "weight", which is their natural order. However, different objects inserted in the priority queue can have the same “weight”. In such cases, I want the priority queue to order them in the same order in which they were queued.
For example, if I add all with the same “weight” to CustomObjects A, B, C, D in this order, then the priority queue should also return them in that order - even if I poll one or more objects before adding them to others.
Here is CompareTo for my custom object:
public int compareTo(CustomObject o) { int thisWeight = this.weight; int thatWeight = o.weight; if(thisWeight < thatWeight){ return -1; } else{ return 1; } }
While I thought that this would maintain this initial order, this is not so. This happens when I enter A, B, C with a weight of 1; Poll A; and add D, E also with weight 1. Somehow, D and E are sorted after B, but before C.
I know that the Iterator for PriorityQueues does not return the correct order, therefore I am limited in my ability to look at the ordering - however, I see the order in which the elements leave the queue, and this clearly does not follow the path I want.
Suggestions?
java priority-queue order
USS1994
source share