Python's collections.deque has a maxlen
argument, such that
[...] the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. [...]
I have been looking for a class that implements the Deque interface in Java, that does the same.
public ArrayDeque(int numElements) looks like numElements
only initializes the deque to that size, but doesn't enforce it as a max length.
Probably not. LinkedHashMap has some facilities to build a cache with eviction policies, but that might be overkill for what you want. Just extend the Deque and add your custom logic ;-)
class MyFixedSizeDeque<T> extends ArrayDeque<T>
{
private int maxSize;
public MyDeque(int size)
{
this.maxSize = size;
}
@Override
public void addLast(T e)
{
this.addLast(e);
if(this.size() > maxSize)
this.removeFirst();
}
}
My Java is a little rusty, and you might want to overload a few more methods (or switch to composition rather than inheritance) but I hope you get the idea...