Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Queue (PriorityQueue) implementation which is also a Set?

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.

like image 778
Mauli Avatar asked Dec 08 '09 18:12

Mauli


People also ask

Is a priority queue a set?

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++

What type of queue is a PriorityQueue?

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.

Is a PriorityQueue always sorted?

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.


2 Answers

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.

like image 127
Andreas Dolk Avatar answered Sep 20 '22 17:09

Andreas Dolk


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.

like image 21
Mac Avatar answered Sep 19 '22 17:09

Mac