Is there a fixed sized queue which removes excessive elements?
Yes, Two
From my own duplicate question with this correct answer, I learned of two:
EvictingQueue
in Google GuavaCircularFifoQueue
in Apache Commons
I made productive use of the Guava EvictingQueue
, worked well.
To instantiate an EvictingQueue
call the static factory method create
and specify your maximum size.
EvictingQueue< Person > people = com.google.common.collect.EvictingQueue.create( 100 ) ; // Set maximum size to 100.
Actually the LinkedHashMap does exactly what you want. You need to override the removeEldestEntry
method.
Example for a queue with max 10 elements:
queue = new LinkedHashMap<Integer, String>()
{
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest)
{
return this.size() > 10;
}
};
If the "removeEldestEntry" returns true, the eldest entry is removed from the map.
I just implemented a fixed size queue this way:
public class LimitedSizeQueue<K> extends ArrayList<K> {
private int maxSize;
public LimitedSizeQueue(int size){
this.maxSize = size;
}
public boolean add(K k){
boolean r = super.add(k);
if (size() > maxSize){
removeRange(0, size() - maxSize);
}
return r;
}
public K getYoungest() {
return get(size() - 1);
}
public K getOldest() {
return get(0);
}
}