Copyque.add(d);
if (que.size() > YOUR_LIMIT)
que.poll();
or did I missunderstand your question?
edit: forgot to mention that for this to work you probably have to invert your comparTo function since it will throw away the one with highest priority each cycle. (if a is "better" b compare (a, b) should return a positvie number.
example to keep the biggest numbers use something like this:
Copypublic int compare(Double first, Double second) {
// keep the biggest values
return first > second ? 1 : -1;
}
Answer from getekha on Stack OverflowCopyque.add(d);
if (que.size() > YOUR_LIMIT)
que.poll();
or did I missunderstand your question?
edit: forgot to mention that for this to work you probably have to invert your comparTo function since it will throw away the one with highest priority each cycle. (if a is "better" b compare (a, b) should return a positvie number.
example to keep the biggest numbers use something like this:
Copypublic int compare(Double first, Double second) {
// keep the biggest values
return first > second ? 1 : -1;
}
MinMaxPriorityQueue, Google Guava
There is indeed a class for maintaining a queue that, when adding an item that would exceed the maximum size of the collection, compares the items to find an item to delete and thereby create room: MinMaxPriorityQueue found in Google Guava as of version 8.
EvictingQueue
By the way, if you merely want deleting the oldest element without doing any comparison of the objects’ values, Google Guava 15 gained the EvictingQueue class.
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 <= 0)is somewhat superfluous because of the next testif (size() < capacity)
I rarely check the return of add methods. I would suggest throwing an exception to indicate the container is full. Add methods that return available space and full state.