How to configure Java Priority Queue to ignore duplicates?

sgarg picture sgarg · May 6, 2012 · Viewed 27.9k times · Source

I thought add() is supposed to ignore duplicates, but my output has duplicates. How do I not store duplicates?

I would also like to know how the priority queue checks if two elements are duplicates. I'm guessing it's using the comparator equals, but I just want to be sure.

Thanks

Answer

Sebastian Łaskawiec picture Sebastian Łaskawiec · May 6, 2012

Here is a part from PriorityQueue Javadoc:

This queue orders elements according to an order specified at construction time, which is specified either according to their natural order (see Comparable), or according to a Comparator, depending on which constructor is used.

So yes, PriorityQueue uses Comparator (if you specified it as a constructor argument) or uses compareTo(...) method (elements must implement Comparable interface).

PriorityQueue allows duplicates. So if you want to avoid that, you need to implement your own version of Queue. You can find very elegant way, how to do that in "Effective Java", page 85. Alternatively you might extend PriorityQueue class and override add method (this is a perfect place to put contains(...) check).