Reputation: 29
Does anyone have any suggestions as to what the best way to modify an object's compareTo function so that when the parent priority queue's "poll()" function is called the lowest non-negative value is returned, as opposed to the lowest value in general?
Say, we have a Number class that stores any number, negative or non-negative, but I don't want the data from an object of that class returned if it's negative.
Upvotes: 1
Views: 1418
Reputation: 12620
Ok, so let's sort things out a little:
A queue in Java can only hold objects, by the way, so you can use null
instead of some other magic value.
I assume you need to allow duplicate values in your implementation. If not, though, have a look at implementations of SortedSet
.
Upvotes: 1
Reputation: 82579
Wrap your Queue inside a wrapper object, and never add negative values. Then you can use your queue as normal, knowing the lowest value will be non-negative.
Here's a rough draft. I didn't compile it or anything, but it's an idea. Here's an example of that.
import java.util.*;
class PositiveQueue<E extends Number> extends PriorityQueue<Number> {
public boolean offer(E e) {
if(isNegative(e)) return false;
return super.offer(e);
}
private static boolean isNegative(Number n) {
// add logic here
return n.intValue() < 0;
}
public static void main(String[] args) {
PositiveQueue<Short> q = new PositiveQueue<Short>();
q.offer((short)4);
q.offer((short)7);
q.offer((short)2);
q.offer((short)-5);
q.offer((short)5);
while(q.peek() != null) System.out.println(q.poll());
}
}
C:\Documents and Settings\glowcoder\My Documents>javac PositiveQueue.java
C:\Documents and Settings\glowcoder\My Documents>java PositiveQueue
2
4
5
7
Upvotes: 3