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.
Well the
PriorityQueue
is going to itself be dependent on theComparitor
or the natural ordering of the items for its sorting, likewise theSet
would be dependent on the natural ordering or theComparitor
function so no I don't think one exists as part of the default Java install...But you could probably create one pretty easily if speed isn't a worry by simply implementing the interfaces you want, and using their natural backings, etc... aka
Unfortunately Java's java.util.* data-set classes aren't always the easiest to extend without rewriting chunks of their code.
The
PriorityQueue
backing is a heap sorted list of elements, so inserting a new element and then doing acontains(e)
test will an O(n) search because sorting is based on the queuing, not on the data value, if you include aHashSet
to support theSet
functionality though, you can improve your lookup time a lot at the expense of maintaining the dataset references twice (remember that Java is pass-by-value and all objects live on the heap). This should improve performance of a large set.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 theadd()
,addAll()
andoffer()
methods like:BTW -
add()
callsoffer()
internally, so maybe it's even enough to just override theoffer()
method and do the check there.PriorityQueue is an AbstractCollection - this has an almost identical interface to a Set. I'm sure it would be easy to make a wrapper that converts a PriorityQueue to a Set. You could keep a side hash table of inserted elements to avoid duplicates, if you really need to enforce that.
I don't think PriorityQueue requires compareTo to be consistent with equals. PriorityQueue doesn't use equals at all (except for its inherited AbstractCollection operations?).
TreeSet
is a set that provides an ordered iterator. It implements theSortedSet
interface, which guarantees that the iterator returned by theiterator
method will return the set's elements in ascending order as determined either by their natural ordering (throughComparable
), or as determined by a comparator given to the set at its creation.