I'm using a priority queue (java.util.PriorityQueue<T>
) where items with the same priority need to be handled in a first-in first-out basis.
I have managed that fine by adding a timestamp member to the item being added to the queue that is incremented for each item added. (See PriorityQueue has objects with the same priority and http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/PriorityBlockingQueue.html )
So using the FIFOEntry class from the docs I have
class FIFOEntry<E extends Comparable<? super E>>
implements Comparable<FIFOEntry<E>> {
final static AtomicLong seq = new AtomicLong();
final long seqNum;
final E entry;
public FIFOEntry(E entry) {
seqNum = seq.getAndIncrement();
this.entry = entry;
}
public E getEntry() { return entry; }
public int compareTo(FIFOEntry<E> other) {
int res = entry.compareTo(other.entry);
if (res == 0 && other.entry != this.entry)
res = (seqNum < other.seqNum ? -1 : 1);
return res;
}
}
What I'd like to do now is to be able to determine if an item is in the queue and/or to be able to remove an item from it. I can't directly use the contains
or remove
functions because the queue holds FIFOEntry objects, not E
ojects.
The contains(Object o)
and the remove(Object o)
functions of the queue depend on the arguments' o.equals(e)
function. I was able to remove items by adding the equals()
function to the FIFOEntry
class that only uses the entry
member for comparison.
I need a better method than this because this new equals
function breaks the "consistent with equals" rule.
Would it be better to create a new, separate class that has a member for entry (same type E) and move the equals()
function to this other class? What about using a Comparator instead?
p.s. More context: this is to be used in Android.