debugjavaMinor
Fixed size priority queue
Viewed 0 times
fixedsizequeuepriority
Problem
I've tried implementing priority queue with fixed size in Java using
I would really appreciate your thoughts, hints and comments.
TreeSet and overriding add() method:public class FixedSizePriorityQueue extends TreeSet {
private final int capacity;
public FixedSizePriorityQueue(final int capacity) {
this.capacity = capacity;
}
public FixedSizePriorityQueue(
final int capacity,
final Comparator comparator) {
super(comparator);
this.capacity = capacity;
}
@Override
public boolean add(final E e) {
// initialized with 0 or less than zero capacity
if (capacity <= 0) {
return false;
}
// keep adding until we fill the queue
if (size() < capacity) {
return super.add(e);
}
if (comparator() != null
&& comparator().compare(this.last(), e) < 0) {
pollLast();
return super.add(e);
}
return false;
}
}I would really appreciate your thoughts, hints and comments.
Solution
Two thoughts:
-
If there is other code and you need all the features of a TreeSet great, otherwise delegate to a TreeSet member variable.
-
Your code `if (capacity
-
If there is other code and you need all the features of a TreeSet great, otherwise delegate to a TreeSet member variable.
-
Your code `if (capacity
Context
StackExchange Code Review Q#30504, answer score: 3
Revisions (0)
No revisions yet.