File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments