Size-limited queue that holds last N elements in Java

后端 未结 8 1408
灰色年华
灰色年华 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 extends ArrayDeque {
    
        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;
        }
    }
    

提交回复
热议问题