Skip to content

Commit 5e0dc8b

Browse files
committed
from StackOverflow
1 parent 6cabb7f commit 5e0dc8b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/FixedSizePriorityQueue.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.Comparator;
2+
import java.util.TreeSet;
3+
4+
// taken from https://stackoverflow.com/questions/7878026/is-there-a-priorityqueue-implementation-with-fixed-capacity-and-custom-comparato
5+
6+
public class FixedSizePriorityQueue<E> extends TreeSet<E> {
7+
8+
private int elementsLeft;
9+
10+
public FixedSizePriorityQueue(int maxSize, Comparator<E> comparator) {
11+
super(comparator);
12+
this.elementsLeft = maxSize;
13+
}
14+
15+
16+
/**
17+
* @return true if element was added, false otherwise
18+
* */
19+
@Override
20+
public boolean add(E e) {
21+
if (elementsLeft == 0 && size() == 0) {
22+
// max size was initiated to zero => just return false
23+
return false;
24+
} else if (elementsLeft > 0) {
25+
// queue isn't full => add element and decrement elementsLeft
26+
boolean added = super.add(e);
27+
if (added) {
28+
elementsLeft--;
29+
}
30+
//System.out.println("Element added: " + e);
31+
//System.out.println("Variable added has value: " + added);
32+
return added;
33+
} else {
34+
// there is already 1 or more elements => compare to the least
35+
int compared = super.comparator().compare(e, this.first());
36+
if (compared == 1) {
37+
// new element is larger than the least in queue => pull the least and add new one to queue
38+
pollFirst();
39+
super.add(e);
40+
return true;
41+
} else {
42+
// new element is less than the least in queue => return false
43+
return false;
44+
}
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)