Size-limited queue that holds last N elements in Java

后端 未结 8 1587
灰色年华
灰色年华 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:22

    I like @FractalizeR solution. But I would in addition keep and return the value from super.add(o)!

    public class LimitedQueue extends LinkedList {
    
        private int limit;
    
        public LimitedQueue(int limit) {
            this.limit = limit;
        }
    
        @Override
        public boolean add(E o) {
            boolean added = super.add(o);
            while (added && size() > limit) {
               super.remove();
            }
            return added;
        }
    }
    

提交回复
热议问题