I'm looking for a PriorityQueue implementation which is also a Set.
The compareTo
implementation if its elements must not have the requirement to be consistent with the implementation of equals
.
Is there somewhere such a implementation for java?
Update: I implemented it now using a SortedSet as the internal collection. So I only had to implement the missing methods to satisfy the queue interface. I also forgot to mention that it also had to be a bounded queue, so it features a capacity and discards the last element of the set if capacity is reached.
By default priority queue is a max-heap, therefore internally for two sets inside the priority queue, the set having a greater first element is the topmost element. If the first element is equal then the second value of sets is compared and so on. Below is the implementation of the min-heap priority queue of set: C++
A priority queue is a special type of queue in which each element is associated with a priority value. And, elements are served on the basis of their priority. That is, higher priority elements are served first. However, if elements with the same priority occur, they are served according to their order in the queue.
A PriorityQueue is what is called a binary heap. It is only ordered/sorted in the sense that the first element is the least. In other word, it only cares about what is in the front of the queue, the rest are "ordered" when needed.
If it's sufficient to have a queue with a 'Set-like' behaviour, iaw you just don't want to accept duplicate entries, then I think, an easy solution could be to subclass PriorityQueue
and override the add()
, addAll()
and offer()
methods like:
@Override
public boolean offer(E e) {
if (contains(e)) {
return false;
} else {
return super.offer(e);
}
}
BTW - add()
calls offer()
internally, so maybe it's even enough to just override the offer()
method and do the check there.
TreeSet
is a set that provides an ordered iterator. It implements the SortedSet
interface, which guarantees that the iterator returned by the iterator
method will return the set's elements in ascending order as determined either by their natural ordering (through Comparable
), or as determined by a comparator given to the set at its creation.
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