Is there a java Deque that implements maxlen, like python collections.deque?

Python collections.deque has an argument maxlen

, so

[...] deque is limited to the specified maximum length. After the division of the limited length is filled, when new items are added, the corresponding number of items are discarded from the opposite end. [...]

I was looking for a class that implements the Deque interface in Java that does the same thing.

public ArrayDeque (int numElements) looks like it numElements

only initializes the deque to this size, but does not apply it as max length.

+3


source to share


1 answer


Probably not. LinkedHashMap has some ability to cache the eviction policies, but that might be overkill for what you want. Just extend Deque and add your own logic; -)


Edit:



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 need to overload a few more methods (or switch to composition rather than inheritance), but I hope you get the idea ...

+1


source







All Articles