Size-limited queue that holds last N elements in Java

后端 未结 8 1398
灰色年华
灰色年华 2020-11-22 13:13

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addi

相关标签:
8条回答
  • 2020-11-22 13:42
        public class ArrayLimitedQueue<E> extends ArrayDeque<E> {
    
        private int limit;
    
        public ArrayLimitedQueue(int limit) {
            super(limit + 1);
            this.limit = limit;
        }
    
        @Override
        public boolean add(E o) {
            boolean added = super.add(o);
            while (added && size() > limit) {
                super.remove();
            }
            return added;
        }
    
        @Override
        public void addLast(E e) {
            super.addLast(e);
            while (size() > limit) {
                super.removeLast();
            }
        }
    
        @Override
        public boolean offerLast(E e) {
            boolean added = super.offerLast(e);
            while (added && size() > limit) {
                super.pollLast();
            }
            return added;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:46

    Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.

    I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):

    public LimitedSizeQueue implements Queue
    {
      private int maxSize;
      private LinkedList storageArea;
    
      public LimitedSizeQueue(final int maxSize)
      {
        this.maxSize = maxSize;
        storageArea = new LinkedList();
      }
    
      public boolean offer(ElementType element)
      {
        if (storageArea.size() < maxSize)
        {
          storageArea.addFirst(element);
        }
        else
        {
          ... remove last element;
          storageArea.addFirst(element);
        }
      }
    
      ... the rest of this class
    

    A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:

    public LimitedSizeQueue<ElementType> implements Queue<ElementType>
    {
        private int maxSize;
        private CircularFifoBuffer storageArea;
    
        public LimitedSizeQueue(final int maxSize)
        {
            if (maxSize > 0)
            {
                this.maxSize = maxSize;
                storateArea = new CircularFifoBuffer(maxSize);
            }
            else
            {
                throw new IllegalArgumentException("blah blah blah");
            }
        }
    
        ... implement the Queue interface using the CircularFifoBuffer class
    }
    0 讨论(0)
提交回复
热议问题