Possible Duplicate:
Java: strange order of queue made from priority queue
I tired to turn a priority queue into a queue by implementing the following comparator:
Here is the code:
import java.util.Comparator;
public class QueueComparator implements Comparator<Square>{
public int compare(Square square1, Square square2)
{
return 1;
}
}
But the resulting "queue" does not keep things in order(FIFO). Why?
The question is why should it?
First your Comparator is completely broken, since it violates the basic constraint that
sign(compare(a,b)) = - sign(compare(b,a))
and
compare(a,a) == 0
So anything using it might come up with all kinds of results like loosing entries, running in an endless loop, throwing a stackoverflow ...
If you want to implement a IDontGiveAShitComparator
it should return 0 all the time. Everything depending on a Comparator should be able to handle that.
What order results is still up to the implementation. If it stores elements in a list FIFO or LIFO are kind of probable, If it stores in a balanced tree, it will probably add elements always on one side, causing rebalancing of the tree, which will pretty much mix everything up.
Maybe it uses something based on hashes, in which case all elements with the same priority might come out ordered by their hash values.
Well, it's a hack. So if it's not working, I wouldn't be too surprised.
The Javadoc of PriorityQueue says:
The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily.
Well, there you have it. If your comparator returns the same value for all pairs of elements, you have nothing but ties. So the queue order is indeed arbitrary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With